camden_kid
camden_kid

Reputation: 12813

TypeScript function type syntax explanation

I'm reading the TypeScript Handbook and in the Functions section under the Function Types heading there is this example (which I understand):

let myAdd = function(x: number, y: number): number { return x+y; };

This is followed by

let’s write the full type of the function out by looking at the each piece of the function type.

and this syntax:

let myAdd: (x: number, y: number) => number =
    function(x: number, y: number): number { return x+y; };

Could someone break this down and explain it as I have never seen this before and can't find an explanation in the handbook?

Upvotes: 3

Views: 2055

Answers (2)

jahilldev
jahilldev

Reputation: 3812

The first line:

let myAdd: (x: number, y: number) => number

Is declaring the type of the variable "myAdd". Typescript can automatically infer this in the first example, alternatively (which the second example shows) you can implicitly tell Typescript what it should expect.

The second line:

function(x: number, y: number): number { return x+y; };

Refers to the type of the function itself which you have assigned to the variable "myAdd".

For a simpler example illustrating the same thing:

let myString: (input: string) => string = (input: string) => input;

Alternatively a different example of implicitly declaring the variables type:

let myNumber: number = 10;

Both of the above tell Typescript what the variable should be.

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164457

This line:

let myAdd: (x: number, y: number) => number =
    function(x: number, y: number): number { return x+y; };

Consists of 3 parts:

(1) The variable declaration, this part is the let myAdd. I assume that there's nothing to add here, it's just like with js.

(2) The type of the variable: (x: number, y: number) => number.
Here we're defining a type of a function that expects two parameters, both of type number, named x and y.
The function needs to return a number.

(3) The assignment of the value to the variable: = function(x: number, y: number): number { return x+y; }.
This is just like javascript as well, except for the added types for the params and return value.
If you look at it you'll see that the actual implementation matches the declared type perfectly.

You can also write it like this:

let myAdd: (x: number, y: number) => number = function(x, y) { return x+y; };

Or:

let myAdd: (x: number, y: number) => number = (x, y) => { return x+y; };

Upvotes: 4

Related Questions