Saman Mohamadi
Saman Mohamadi

Reputation: 4672

Typescript, Class has no index signature

A simple implementation of the my code is like this:

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.
  }
}

how can I add index signature to the Foo class?

Upvotes: 0

Views: 2982

Answers (1)

Saravana
Saravana

Reputation: 40712

You have to implement the indexer defined in the interface

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
  }
}

Your example actually does not throw an error even without the indexer implementation because Foo has member bar which can be used with the index notation without defining an indexer.

Upvotes: 2

Related Questions