-2

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']

Chris
  • 11,108
  • 21
  • 70
  • 137

1 Answers1

0

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.)

ethan.roday
  • 2,269
  • 20
  • 26
  • One use case which I'm currently struggling with is having the individual properties depend on one another. The example is I'm building a Class that has static members that build a store of API endpoints. For example, I have "/api1/", "/api2/" as two static members, and later, extensions of those endpoints are additional static members. You can't have these types of self references if you use an enum or an object, correct? – Adam P. Aug 21 '21 at 14:08
  • @AdamP. I think you're probably better off asking this as a separate question and outlining your situation in some more detail (preferably with an example) - it's hard to know what the right approach is given your comment. – ethan.roday Aug 23 '21 at 00:26