Skip to content
Advertisement

js get list of own static properties

I have a class with static properties and I want to get a list of all property values:

class TimeRange {
    static ALL = 'all time'
    static MONTH = 'month'
    static WEEK = 'week'
    static DAY = 'day'
}

Now I want to get: ['all time', 'month', 'week', 'day']

Advertisement

Answer

What’s your use case here? If you’re looking for a way to have some properties that you can iterate through but also refer to by key, then you can just use a normal object:

const timeRanges = {
  ALL: 'all time',
  MONTH: 'month',
  WEEK: 'week',
  DAY: 'day'
}
timeRanges.ALL; // 'all time'
timeRanges.MINUTE; // not allowed
Object.keys(timeRanges).map(key => timeRanges[key]); // ['all time', 'month', 'week', 'day']

Classes are not really designed to have their properties iterated through. However, if they absolutely must be in a class, you could turn them into instance properties follow the method outlined here:

class TimeRange {
  ALL = 'all time'
  MONTH = 'month'
  WEEK = 'week'
  DAY = 'day'
}
Object.getOwnPropertyNames(new TimeRange()); // ['all time', 'month', 'week', 'day'] 

That’s somewhat of an anti-pattern, though.

One final option you might consider would be to use a string enum:

enum TimeRange {
  ALL = 'all time',
  MONTH = 'month',
  WEEK = 'week',
  DAY = 'day'
}
Object.keys(TimeRange).map(key => TimeRange[key]); // ['all time', 'month', 'week', 'day']

(To clarify, I’m assuming you’re using Typescript here based on the tags in the question. If you’re not, then the comments on your original question stand. You could still use options 1 and 2 that I suggest here, but obviously without the type checking benefits.)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement