我如何使用反射API获取数组项类型打字稿? [英] How do I get array item type in TypeScript using the Reflection API?

查看:137
本文介绍了我如何使用反射API获取数组项类型打字稿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在打字稿以下的小类,有一些公共领域的装饰:

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.

我的房屋装饰功能:

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.

请注意:我需要实例化之前的型号说明,正因为如此,它是不可能使用数组项动态确定类型:有没有数组项,甚至没有一个Array实例

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.

推荐答案

我不认为这是可能的,截至目前。如果您看到生成的js文件,对于任何数组,它创建了类型数组元不会对任何类型的信息。

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);

有关内建类型,我能想到的解决这个问题的方法之一是通过在装饰本身的类型和装饰code编写自定义的逻辑。

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

这篇关于我如何使用反射API获取数组项类型打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆