typescripttypescript2.4

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


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?


Solution

  • 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;
    }