我有一个可以由用户扩展的类,如下所示:
class Foo {
extendFoo(key: string, value: string) {
this[key] = value; //<==typescript error: missing index signature
}
}
如您所见,this
可以使用字符串进行扩展。问题是打字稿抱怨因为我没有索引签名,所以我尝试添加一个:
class Foo {
[key: string]: string;
extendFoo(key: string, value: string) { //<==typescript error: extendFoo is not a string
this[key] = value;
}
}
如何添加索引签名,但仍允许在我的类中使用方法?
当然,我可以将索引签名更改为[key: string]: string | Function
,但这不正确 - 任何未知键都必须是字符串。如何仅从extendFoo
索引签名中排除?
class Foo {
[key: string]: string | Function;
extendFoo(key: string, value: string) {
this[key] = value;
}
}
const test = new Foo();
test['some unknown prop'].includes('test'); //<== typescript error: 'Property 'includes' does not exist on type 'Function'
顺便说一句,我知道扩展是一种不好的模式this
,但是我正在将遗留代码转换为打字稿并且别无选择。