简体   繁体   中英

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?

eg 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) .

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

Scan the Object.keys(Foo.prototype)

If you just one to list the field's name from a class you can use the following:

let fields = Object.keys(myObj) as Array<MyClass>;

Hope it helps.

You need to instantiate const a = new Foo(); and access using Object.keys

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

const a = new Foo();
console.log(Object.keys(a)); // ["prop"]

DEMO

EDIT: If you want to get from the type it is not possible since types won't be available once the code is compiled.

Since the code above will be transpiled to following js code:

var Foo = (function () {
    function Foo(one, two, three) {
        this.one = one;
        this.two = two;
        this.three = three;
    }
    return Foo;
}());

I'd first extract the constructor using const c = Foo.prototype.constructor and the get the name of arguments from that. This thread shows how to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM