Almis Almis - 3 months ago 6
Javascript Question

Get all static getters in a class

Let's say I have this class (which I using like an enum):

class Color {
static get Red() {
return 0;
}
static get Black() {
return 1;
}
}


Is there anything similar to
Object.keys
to get
['Red', 'Black']
?

I'm using Node.js v6.5.0 which means some features might be missing.

Answer

Use Object.getOwnPropertyDescriptors() and filter the results to contain only properties which have getters:

class Color {
    static get Red() {
        return 0;
    }
    static get Black() {
        return 1;
    }
}

const getters = Object.entries(Object.getOwnPropertyDescriptors(Color))
  .filter(([key, descriptor]) => typeof descriptor.get === 'function')
  .map(([key]) => key)

console.log(getters)

You can also try this approach—it should work in Node.js 6.5.0.

class Color {
    static get Red() {
        return 0;
    }
    static get Black() {
        return 1;
    }
}

const getters = Object.getOwnPropertyNames(Color)
  .map(key => [key, Object.getOwnPropertyDescriptor(Color, key)])
  .filter(([key, descriptor]) => typeof descriptor.get === 'function')
  .map(([key]) => key)

console.log(getters)