现在这段代码没有错误,Typescript 编译器认为它完全有效,但它们是一样的吗?有人可以解释这两种类型定义之间的区别,并为它们中的每一种提供良好的用例示例。
const b = () =>'hello'
const x: ()=>string = b
const y: {():string} = b
最佳答案
它们是一样的。
如果您愿意,第二种形式确实为您提供了添加其他静态属性的选项。
type FunctionWithId = {
(): string;
id: number;
}
const b = () => 'hello'
b.id = 4;
const x: FunctionWithId = b
也可以使用第二个版本来做函数重载:
type Example = {
(x: number): number;
(x: string): string;
}
因此,如果您需要其中一些额外功能,请使用第二种语法。如果不是,两者都可以,而且您可能会更频繁地看到第一个,因为它更简单。
关于typescript - ()=>any 和 {() :any} in Typescript 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64598389/