【问题标题】:Typescript, Class has no index signature打字稿,类没有索引签名
【发布时间】:2017-05-01 07:03:14
【问题描述】:

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

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 类添加索引签名?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你必须实现接口中定义的索引器

    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 可以与索引符号一起使用而无需定义索引器。

    【讨论】:

    • 我也认为在我的示例中它不应该抛出错误,但确实如此! error TS7017
    • 你使用的是什么版本的 TypeScript?
    • 版本:2.1.5
    • 是的 gulp-typescript 和 phpstrom typescript 插件。
    • 不使用 IDE。您是否可以通过从命令行运行tsc 进行编译?同时发布您的 tsconfig.json
    猜你喜欢
    • 2018-12-15
    • 2019-05-23
    • 1970-01-01
    • 2021-05-20
    • 2018-09-05
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多