How to declare one type for all class methods in typescript

Viewed 53

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 Answers

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.

Related