typescript - 实现 Typescript 类接口(interface)不保留方法类型

标签 typescript

我正在尝试编写一个 Typescript 接口(interface),然后编写一个实现该接口(interface)的类。

问题是我似乎无法从接口(interface)获取方法签名以应用于类。

这是一个精简的示例:

export interface Foo {
  bar(value: string): void;
}


export class MyFoo implements Foo {
  // ✔️ Typescript error:
  // Property 'bar' is missing in type 'MyFoo' but required in type 'Foo'
}


export class MyFoo implements Foo {
  // value is inferred as `any` instead of `string`, 
  // and there aren't any errors with the return type mismatch
  bar(value) { return true; }
}


似乎编译器知道 bar方法应该存在,但由于某种原因不保留它的签名。

最佳答案

t seems that the compiler is aware that the bar method should exist, but doesn't preserve the signature of it for some reason.



正确的。原因如下:https://github.com/Microsoft/TypeScript/pull/6118#issuecomment-216595207

因此,开发人员有责任添加他们需要的注释。

关于typescript - 实现 Typescript 类接口(interface)不保留方法类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60308798/

相关文章:

javascript - TypeScript - 将 HTML 附加到 Angular 2 中的容器元素

javascript - TypeScript 是否可以从动态对象推断键?

javascript - Angular - 使用 ngFor 创建 Accordion 菜单。需要自动关闭并在单击时打开另一个

angular - 模块 '"node_modules/@angular/core/core "' has no exported member ' OpaqueToken'

javascript - 'string | null' 类型的参数不可分配给 'ValueFn<SVGPathElement, Datum[], string | number | boolean | null>' 类型的参数

angular - 类型错误 : Cannot read property 'get' of undefined Ionic 3/Angular 5

angularjs - 错误 TS2339 : Property 'endsWith' does not exist on type 'string'

reactjs - React 未定义(无法读取未定义的属性 'createElement')

typescript - angular2 router.navigate inside auth0 回调

angular - 传递函数给子组件, 'this' 上下文错误