Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get properties of a type as an array in Typescript?

Given the following type:

class Foo {
    constructor(
        private one: string, 
        private two: string, 
        private three: string) {
    }
}

How can I have an array whose values are the type's properties?

e.g. I need to be able to get an array as:

['One', 'Two', 'Three']

Note I need to have the properties extracted from a type and not an instance otherwise I could simply use Object.keys(instanceOfFoo).

like image 581
MaYaN Avatar asked Oct 29 '25 17:10

MaYaN


1 Answers

You can use Reflect.construct() to get the keys, then use Object.keys() to convert that to an array.

Note: if the key doesn't have a default it won't be generated as you can see with four.

class Foo {
  constructor() {
    this.one = ''
    this.two = ''
    this.three = ''
    this.four
  }
}

console.log(Object.keys(Reflect.construct(Foo, [])))
like image 132
Get Off My Lawn Avatar answered Oct 31 '25 07:10

Get Off My Lawn