Writing the function type

Writing the function type

Now that we’ve typed the function, let’s write the full type of the function out by looking at the each piece of the function type.

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

A function’s type has the same two parts: the type of the arguments and the return type. When writing out the whole function type, both parts are required. We write out the parameter types just like a parameter list, giving each parameter a name and a type. This name is just to help with readability. We could have instead written:

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

As long as the parameter types line up, it’s considered a valid type for the function, regardless of the names you give the parameters in the function type.

The second part is the return type. We make it clear which is the return type by using a fat arrow (=>) between the parameters and the return type. As mentioned before, this is a required part of the function type, so if the function doesn’t return a value, you would use void instead of leaving it off.

Of note, only the parameters and the return type make up the function type. Captured variables are not reflected in the type. In effect, captured variables are part of the “hidden state” of any function and do not make up its API.

doc_TypeScript
2016-10-04 19:25:46
Comments
Leave a Comment

Please login to continue.