首页 > 解决方案 > Typescript 中 ()=>any 和 {():any} 有什么区别

问题描述

现在这段代码没有错误,Typescript 编译器认为它是完全有效的,但它们是否相同?有人可以解释这两种类型定义之间的区别,并为它们中的每一种都提供很好的用例示例。

const b = () =>'hello'

const x: ()=>string = b
const y: {():string} = b

标签: typescript

解决方案


他们是一样的。

如果需要,第二种形式确实为您提供了添加其他静态属性的选项。

type FunctionWithId = {
    (): string;
    id: number;
}

const b = () => 'hello'
b.id = 4;
const x: FunctionWithId = b

也可以使用第二个版本进行函数重载:

type Example = {
  (x: number): number;
  (x: string): string;
}

因此,如果您需要其中一些额外功能,请使用第二种语法。如果不是,也可以,而且您可能会更频繁地看到第一个,因为它更简单。


推荐阅读