Get all static getters in a class

Let's say I have this class (which I use as an enumeration):

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

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

I am using Node.js v6.5.0, which means that some functions may be missing.

+4
source share
1 answer

Use Object.getOwnPropertyDescriptors()and filter the results so that they only contain properties that 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)
Run codeHide result

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)
Run codeHide result
+10
source

Source: https://habr.com/ru/post/1653549/


All Articles