【发布时间】:2015-07-08 21:22:39
【问题描述】:
问题
如何将类型检查添加到动态创建的类方法中?
示例
给定一个非常简单的Property 类。
class Property {
value: any;
name: string;
constructor(name: string, value: any) {
this.name = name;
this.value = value
}
}
还有一个Entity 类
class Entity {
name: string;
properties: Property[];
constructor(name: string, properties: Property[]) {
this.name = name;
this.properties = properties;
this.properties.forEach((p: Property, index: number) => {
this[p.name] = (value: string): any => {
if (value) {
this.properties[index].value = value;
}
return this.properties[index].value;
}
}, this);
}
}
重要部分:this[p.name] = function ...(我们不知道“transpile”时方法的名称)。
我们在转成 javascript 时遇到如下错误:
var car = new domain.Entity(
'car',
[
new domain.Property('manufacturer', 'Ford'),
new domain.Property('model', 'Focus')
]
);
car.model() // error TS2339: Property 'model' does not exist on type 'Entity'.
我知道这是类的不常见用法,因为Entity 的不同实例将定义不同的方法。有没有办法消除错误,即 typescript 能够识别每个实例的正确界面,或者至少 消除错误?
注意事项
这是有效的 javascript,可以通过以下方式使用它:
var car = new domain.Entity(
'car',
[
new domain.Property('manufacturer', 'Ford'),
new domain.Property('model', 'Focus')
]
);
car.model() // 'Focus'
car.model('Transit') // 'Transit'
我知道这是在 similar question 上提出的,但这种情况略有不同,因为方法名称也是在运行时定义的。
【问题讨论】:
标签: typescript