Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function type annotation typescript

Tags:

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? 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.

What is the reason that I have to define names like x and y in the function type? Isn't typescript able to infer function type (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.

like image 227
Peter Avatar asked Oct 19 '22 12:10

Peter


1 Answers

Consider for example the declaration of the 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.

like image 54
Kutyel Avatar answered Nov 15 '22 05:11

Kutyel