my代码的简单实现如下所示:
interface IndexSignature{
[key:string]:any;
}
class Foo implements IndexSignature{
bar(){};
baz(){
this['bar'](); //Error: Element implicitly has an 'any' type because type 'Foo' has no index signature.
}
}如何将索引签名添加到Foo类?
发布于 2017-05-01 15:32:51
您必须实现接口中定义的索引器
interface IndexSignature {
[key: string]: any;
}
class Foo implements IndexSignature {
[key: string]: any;
bar() { };
baz() {
this['bar']();
let something = this["something"]; // throws before indexer implementation, no longer throws
}
}即使没有索引器实现,您的示例实际上也不会抛出错误,因为Foo具有成员bar,该成员可以与索引表示法一起使用,而无需定义索引器。
https://stackoverflow.com/questions/43715507
复制相似问题