【问题标题】:How to declare one type for all class methods in typescript如何为打字稿中的所有类方法声明一种类型
【发布时间】:2021-06-06 18:43:12
【问题描述】:

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

像这样:

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

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

  genarator2 = () => "text2
}

TextGenerator 中的错误:

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

【问题讨论】:

标签: typescript


【解决方案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
}

我实际上不知道为什么需要这样做,所以如果你发现了,请告诉我。

【讨论】:

  • 嘿,它打破了关键。试试看:type AvailableTextGenerators = keyof TextGenerator
猜你喜欢
  • 2022-11-02
  • 2022-08-22
  • 2019-02-16
  • 1970-01-01
  • 2021-01-12
  • 2019-11-12
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多