Zen*_*tzi 5 types interface class typescript
interface IFoo {
  method: (ha: string) => void;
}
class Foo implements IFoo {
  public method(ha) {}
}
将鼠标悬停在类方法中的“ha”参数会显示
参数“ha”隐式具有“any”类型,但可以从使用中推断出更好的类型
既然类实现了接口,那么它不应该与接口类型匹配吗?如果您尝试为参数“ha”指定与字符串不同的类型,例如数字,它会出错,因为它不能分配给字符串类型,这是有道理的。
那么,为什么我需要在接口和类中都分配 ha 的类型呢?这是有意的行为吗?
目前,TypeScript 不支持这一点。
您可以在这里了解更多信息:https ://github.com/Microsoft/TypeScript/issues/23911
这不是一个简单的任务。
这是因为 TypeScript 构建在 JavaScript 之上,并且没有像 C# 等其他语言那样的接口解析。
为了给您一些基本概念,假设您有两个接口X,并且Y两者都有相同的方法但类型不同:
interface X { foo(i: string): string }
interface Y { foo(x: number): number }
创建实现这两个接口的类时,不能像这样将这些接口组合在一起:
class K implements X, Y {
  // error: this does not satisfy either interfaces.
  foo(x: number | string): number | string {
    return x
  }
}
对于这个简单的示例,您需要:
class K implements X, Y {
  foo(x: number): number
  foo(x: string): string
  foo(x: number | string): number | string {
    return x
  }
}
即使这也不理想,因为它不强制输入类型与输出类型匹配。