网站搜索

如何在 TypeScript 中为所有类方法声明一种类型


我想强制所有方法返回相同的类型。

像这样:

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

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

  genarator2 = () => "text2
}

TextGenerator 中的错误:

类 'TextGenerator' 错误地实现了接口 'ITextGenerator'。类型 'TextGenerator' 中缺少索引签名。

答案#1

你可以做以下操作来使它工作:

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
}

我实际上不知道为什么需要这个,所以如果你弄明白了,请告诉我。