gpt4 book ai didi

typescript 函数类型

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

我是 Typescript 的新手,正在探索函数类型。请帮助我理解为什么以下代码段没有引发错误。

interface Person {
firstName: string,
age?: number,
sayHello(name: string): void
}

let chethan:Person = {
firstName: "chethan",
sayHello: function() {
return 1;
}
}

正如您在这里看到的,在我的界面中我提到 sayHello 应该接受一个字符串并返回 void。但是当我给“chethan”obj 一个默认值时,sayHello 不接受字符串参数并且还返回数字而不是 void。但是 Typescript 没有抛出任何错误。

最佳答案

这是预期的行为。另一种思考方式是返回 void 的回调类型表示“我不会查看你的返回值,如果存在的话”。

您可以在此处找到更多相关信息:https://github.com/microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void

如果你想要类型安全,只接受void。您可以直接在对象中的函数上键入它。

sayHello: function():void {
return 1; // should give an error
}

关于 typescript 函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74730905/

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