()=>;之间的区别是什么;Typescript中的any和{():any} 现在这个代码没有错误,TypScript编译器认为它是完全有效的,但它们是一样的吗?有人能解释这两种类型定义之间的区别吗?并为每一种类型定义给出良好的用例示例 const b = () =>'hello' const x: ()=>string = b const y: {():string} = b

()=>;之间的区别是什么;Typescript中的any和{():any} 现在这个代码没有错误,TypScript编译器认为它是完全有效的,但它们是一样的吗?有人能解释这两种类型定义之间的区别吗?并为每一种类型定义给出良好的用例示例 const b = () =>'hello' const x: ()=>string = b const y: {():string} = b,typescript,Typescript,它们是一样的 第二个表单确实提供了添加其他静态属性的选项(如果需要) type FunctionWithId = { (): string; id: number; } const b = () => 'hello' b.id = 4; const x: FunctionWithId = b 也可以使用第二个版本进行函数重载: type Example = { (x: number): number; (x: string): string; } 因此,如果您

它们是一样的

第二个表单确实提供了添加其他静态属性的选项(如果需要)

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

const b = () => 'hello'
b.id = 4;
const x: FunctionWithId = b
也可以使用第二个版本进行函数重载:

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

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

btw,第一个表单上的函数重载看起来像
((x:number)=>number)和((x:string)=>string)