首页 > 解决方案 > 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).

标签: javascripttypescript

解决方案


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, [])))


推荐阅读