How do I get array item type in TypeScript using t

2020-05-21 04:18发布

I have the following little class in TypeScript, with some public fields decorated:

class Company {
    @dataMember
    public name: string;

    @dataMember
    public people: Person[];
}

class Person {
    // ...
}

By using reflect metadata, I can determine the types of Company properties name and people: they are the constructor functions String and Array, respectively, which is expected and logical.

My property decorator function:

function decorate(target: Object, propertyKey: string | symbol): void {
    var reflectType = Reflect.getMetadata("design:type", target, propertyKey);
    // ...
}

But how could I determine the type (constructor function) of array elements? Is it even possible? In the above example, it should be (a reference to) Person.


Note: I need the type reference before instantiation, and because of this, it is impossible to dynamically determine the type using array items: there are no array items, there isn't even an Array instance.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-05-21 04:49

I don't think this is possible as of now. If you see the generated js file, for array of anything, it creates metadata with type as Array without any information on type.

__decorate([
    dataMember_1.dataMember, 
    __metadata('design:type', Array)
], Company.prototype, "people", void 0);

For built-in types, one way I could think of solving this problem is to pass the type in the decorator itself and writing the custom logic in the decorator code.

@dataMember(String)
myProp: Array<String>

For Custom objects, most of the time when the decorator call is fired, the module is not fully loaded. So, one way is to pass the class name and parse it later.

@dataMember("People")
people: People[]
查看更多
登录 后发表回答