【发布时间】:2020-06-27 14:47:41
【问题描述】:
我有一个可以像这样由用户扩展的类:
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 是一种不好的模式,但我正在将旧代码转换为打字稿并且别无选择。
【问题讨论】:
-
这能回答你的问题吗? Typescript index signature and methods
-
this 适合您吗?如果是这样,我会写下来。
-
@DaGardner,我在问这个问题之前偶然发现了这个链接,但这对我的情况不利。建议的解决方案是我在第三个代码中剪掉的,我解释了为什么它对我来说不够好。
-
@jcalz,这是一个有趣的解决方案。如何在 cmets 中发送链接?太长了,不想和大家分享了
标签: typescript class methods index-signature