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:

JavaScript

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:

JavaScript

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:

JavaScript

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

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

JavaScript

(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