Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 305
Almis Avatar asked Sep 03 '16 20:09

Almis


1 Answers

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)
like image 154
Michał Perłakowski Avatar answered Nov 03 '22 13:11

Michał Perłakowski