2

I want to force all methods return the same type.

Like this:

interface ITextGenerator {
  [key: string]: () => string
}

class TextGenerator implements ITextGenerator {
  genarator1 = () => "text1"

  genarator2 = () => "text2
}

Error in TextGenerator:

Class 'TextGenerator' incorrectly implements interface 'ITextGenerator'. Index signature is missing in type 'TextGenerator'.

  • 1
    You can add the index signature to the class like so: https://tsplay.dev/mMyvZm – Linda Paiste Jun 06 '21 at 19:22
  • 1
    Does this answer your question? [Can I define a Typescript class which has an index signature?](https://stackoverflow.com/questions/31977481/can-i-define-a-typescript-class-which-has-an-index-signature) – aleksxor Jun 06 '21 at 21:04

1 Answers1

1

You can do the following to make it work:

interface ITextGenerator {
  [key: string]:  () => string;
}

class TextGenerator implements ITextGenerator{

  [key: string]:  () => string; // This is important but i think kinda redundant

  test = () => '33'; // this is fine
  error = 33; // this is not okay
}

I actually don't know the reason why this is needed so if you find out let me know.

thecOdemOnkey
  • 271
  • 2
  • 6