我想在打字稿中使用原型。
export class base{
constructor() {
base.prototype["g"] = new option({});
}
}
第3行显示:[ts]元素隐含有一个' any'因为类型' base'没有索引签名。
帮助!
答案 0 :(得分:1)
您可以将索引签名添加到base
类:
export class base{
[prop: string]: option
constructor() {
base.prototype["g"] = new option({});
}
}
但这样做意味着您通过base
实例上的索引签名访问的任何属性也将被键入为option
。例如:
let doesNotExist = new base()["doesNotExist"]; // Will compile fine without throwing error.
如果您只想为原型添加一组有限的属性,您可以单独添加这些属性:
export class base{
g: option
constructor() {
base.prototype["g"] = new option({});
}
}
let g = new base()["g"] // OK
let doesNotExist = new base()["doesNotExist"] // Error