"Function Types", What's the difference and why are they useful?

153 Views Asked by At

In the TS docs over at: https://www.typescriptlang.org/docs/handbook/functions.html, "Function Types" are introduced. The code for such an example is:

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

Where as for the "non-typed" function it is

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

To me, the extra syntax in the first example is very strange. Why is there arrow-function syntax for the return type? Why are there two parameter specifications?

1

There are 1 best solutions below

6
On BEST ANSWER

Typing the function is useful if you don't know what the function will be when the variable is declared:

let myOperation: (x: number, y: number) => number;

if ( // some condition ) {
  myOperation = function (x: number, y: number): number { return x + y; };
} else {
  myOperation = function (x: number, y: number): number { return x * y; }
}

Note that in some places (e.g. interfaces) you can describe the type with or without the arrow:

interface WithoutArrow {
  operation(x: number, y: number): number;
}

interface WithArrow {
  operation: (x: number, y: number) => number;
}