gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:40:03 25 4
gpt4 key购买 nike

我正在尝试编写一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com