Search code examples
functiontypescripttypestypescript-2.5

Why are these two function types in typescript different?


Using typescript, I'm finding why two different functions assigned to different local variables result in different signatures. I thought one was just more explicit.

let a: (number)=>number =
  function(x: number): number {return 42;};

let z = function(x:number): number { return 42; };

> .type a
let a: (number: any) => number
> .type z
let z: (x: number) => number

I thought a was just a more explicit version of writing z, but somehow it gets typed more liberally as accepting any.

Using Typescript version 2.5.2


Solution

  • let a: (number)=>number
    

    The parameter name is required. This is exactly equivalent to:

    let a: (number: any)=>number
    

    In other words, the first number here defines a parameter named "number"

    What you need is,

    let a: (x: number)=>number =
      function(x: number): number {return 42;};
    

    The name, x, doesn't matter.