我在 TypeScript 中有以下小类,装饰了一些公共(public)字段:
class Company {
@dataMember
public name: string;
@dataMember
public people: Person[];
}
class Person {
// ...
}
通过使用 reflect metadata , 我可以确定公司属性 name 和 people 的类型:它们是构造函数 String 和 Array,分别是预期的和合乎逻辑的。
我的属性装饰器函数:
function decorate(target: Object, propertyKey: string | symbol): void {
var reflectType = Reflect.getMetadata("design:type", target, propertyKey);
// ...
}
但是我如何确定数组元素的类型(构造函数)?有可能吗?在上面的示例中,它应该是(对)Person 的引用。
注意:我在实例化之前需要类型引用,因此,无法使用数组项动态确定类型:没有数组项,甚至没有 Array 实例。
最佳答案
目前我认为这是不可能的。如果您看到生成的 js 文件,对于任何数组,它会创建类型为 Array 的元数据,而没有任何类型信息。
__decorate([
dataMember_1.dataMember,
__metadata('design:type', Array)
], Company.prototype, "people", void 0);
对于内置类型,我能想到的解决这个问题的一种方法是在装饰器本身中传递类型,并在装饰器代码中编写自定义逻辑。
@dataMember(String)
myProp: Array<String>
对于自定义对象,大部分时间当装饰器调用被触发时,模块没有完全加载。因此,一种方法是传递类名并稍后对其进行解析。
@dataMember("People")
people: People[]
关于arrays - 如何使用反射 API 在 TypeScript 中获取数组项类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35022658/