typescript - 在接口(interface)中使用胖箭头和非胖箭头语法声明函数有什么区别?

标签 typescript overloading function-expression

在 TypeScript 的接口(interface)和类型中使用胖箭头和非胖箭头语法声明函数有什么区别?
例如:

build(paramOne: string): string;
相比:
build: (paramOne: string) => string;
起初,我认为它会限制我实现功能的方式,但似乎并非如此。所以,我认为这与 this 无关。就像在 ES6 中一样。但是我确实注意到,当我尝试重载时,以胖箭头语法声明的那个有问题。
例如,这是 Not Acceptable :
build: (paramOne: string) => void
build: (paramOne: number, paramTwo: string) => void
这将给出一个错误:
Subsequent property declarations must have the same type. Property 'build' must be of type '{ (paramOne: string): string; (paramOne: number, paramTwo: string): number; }', but here has type '(params: unknown) => void
但这没关系:
build(paramOne: string): string;
build(paramOne: number, paramTwo: string): number;
那么,这两种语法是否相同?是否有任何差异或场景我应该使用一个而不是另一个?

最佳答案

主要区别在于带有箭头的语法是 function type expression , 而另一个是 call signature .明显的区别是手册中的语法:

Note that the syntax is slightly different compared to a function type expression - use : between the parameter list and the return type rather than =>.


您是正确的,此语法不会使 this函数的词法范围。您可以指定任何 this键入您希望函数在调用时具有的类型:
thisChanged: (this: { test: number }, param1: number, param2: boolean) => string;
但正如您也正确猜到的那样,应用程序存在细微差别。请注意术语表达式而不是签名。前者“评估”到一个调用签名,除非定义为表达式的交集,而后者可以定义多次以创建 function overloads :
//multiple call signatures used for function overloading:
function build(param1: string) : string;
function build(param1: number) : string;
function build(param1: string | number) {
    return param1.toString();
}

//intersection of expressions 
type build2 = ((param1:string) => string) & ((param1:number) => string);

declare const b: build2;
b(2) //OK
b("test") //OK
b(false) //No overload matches this call.
应用于您在 object types 中使用它们的用例,调用签名可以在同一个键下多次指定,因为这会导致多个函数重载。另一方面,[key]: <function expression>语法定义具有函数表达式类型值的属性(因此无法多次指定属性,因为键必须是唯一的)。
另请注意,推断的类型对应于函数的定义方式(作为函数声明或表达式):
//call signature: function build3(param1: string | number): string
function build3(param1: string|number) : string {
    return param1.toString();
}

//function expression: const build4: (param1: string | number) => string
const build4 = (param1: string|number) : string => param1.toString();

Playground

关于typescript - 在接口(interface)中使用胖箭头和非胖箭头语法声明函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66813579/

相关文章:

typescript - 解决VS 2017中的 'Conflicting definitions for node' TS4090错误

javascript - 删除 Angular-Node-Passport 身份验证中的浏览器历史记录

vba - 重载属性

javascript - JavaScript 混淆中的函数表达式

javascript - 函数表达式参数未赋值,但有值

Javascript:将变量定义为调用相同函数的匿名函数

angular - 如何使用 TypeScript 提取接口(interface)的属性(最好没有第 3 方库)

javascript - 使用 javascript rrule.min.js 实现 RRule

c++ - 如何返回3个值之间的最大值?

c++ - 函数重载,无法推导出模板参数