Typescript,Class没有索引签名

时间:2017-05-01 07:03:14

标签: typescript

我的代码的简单实现是这样的:

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类?

1 个答案:

答案 0 :(得分:0)

您必须实现接口

中定义的索引器
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,可以在不定义索引器的情况下与索引表示法一起使用。

相关问题