简体   繁体   English

函数类型注释打字稿

[英]Function type annotation typescript

I wonder what the meaning is of type annotating a function as below when the formal parameter names does not have to match: 我想知道当形式参数名称不必匹配时,类型注释函数的含义是什么:

let foo: (x:number, y:number) => number = (a:number, b:number) => a+b    

I mean, what is the meaning of (x:number, y:number) => number ? 我的意思是, (x:number, y:number) => number什么意思? I think it would make more sense if I could write (number, number) => number when defining the function type, especially if the 'formal parameter names' does not have to match anyway. 我认为如果我在定义函数类型时可以编写(number, number) => number会更有意义,特别是如果'形式参数名称'无论如何都不匹配。

What is the reason that I have to define names like x and y in the function type? 我必须在函数类型中定义xy等名称的原因是什么? Isn't typescript able to infer function type (a:number, b:number) => number ? 打字稿能不能推断出函数类型(a:number, b:number) => number And I know I can just omit the explicit type annotation, but in my case I always want explicit type annotations. 我知道我可以省略显式类型注释,但在我的情况下,我总是想要显式类型注释。

Consider for example the declaration of the Array.prototype.map() : 例如,考虑Array.prototype.map()的声明:

public map(mapper: (value?: T, index?: number, list?: T[]) => any): any[];

You need the variable names cause they have important information about the arguments that the method expects, just the types are not enough. 您需要变量名称,因为它们具有关于方法所期望的参数的重要信息,只是类型不够。 As you said, you could avoid the types but this way you are giving the one using your code as much info as possible about your method. 正如你所说,你可以避免使用类型,但这样你就可以使用代码尽可能多地提供有关方法的信息。

The response is in the Typescript FAQ 响应在Typescript FAQ中

It's not stated there, but it seems like a decision made in order to make the documentation more readable, as the parameter name possibly hints about the parameter value. 它没有在那里声明,但似乎是为了使文档更具可读性而做出的决定,因为参数名称可能暗示了参数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM