4.11 Arrow Functions

Arrow functions are extended from JavaScript to optionally include parameter and return type annotations.

  ArrowFormalParameters: ( Modified )   CallSignature

The descriptions of function declarations provided in chapter 6 apply to arrow functions as well, except that arrow functions do not support overloading.

The type of an arrow function is determined in the same manner as a function expression (section 4.10). Likewise, parameters of an arrow function and return statements in the body of an arrow function are contextually typed in the same manner as for function expressions.

When an arrow function with an expression body and no return type annotation is contextually typed (section 4.23) by a function type T and a contextual signature S can be extracted from T, the expression body is contextually typed by the return type of S.

An arrow function expression of the form

  1. ( ... ) => expr

is exactly equivalent to

  1. ( ... ) => { return expr ; }

Furthermore, arrow function expressions of the forms

  1. id => { ... }
  2. id => expr

are exactly equivalent to

  1. ( id ) => { ... }
  2. ( id ) => expr

Thus, the following examples are all equivalent:

  1. (x) => { return Math.sin(x); }
  2. (x) => Math.sin(x)
  3. x => { return Math.sin(x); }
  4. x => Math.sin(x)

A function expression introduces a new dynamically bound this, whereas an arrow function expression preserves the this of its enclosing context. Arrow function expressions are particularly useful for writing callbacks, which otherwise often have an undefined or unexpected this.

In the example

  1. class Messenger {
  2. message = "Hello World";
  3. start() {
  4. setTimeout(() => alert(this.message), 3000);
  5. }
  6. };
  7. var messenger = new Messenger();
  8. messenger.start();

the use of an arrow function expression causes the callback to have the same this as the surrounding ‘start’ method. Writing the callback as a standard function expression it becomes necessary to manually arrange access to the surrounding this, for example by copying it into a local variable:

  1. class Messenger {
  2. message = "Hello World";
  3. start() {
  4. var _this = this;
  5. setTimeout(function() { alert(_this.message); }, 3000);
  6. }
  7. };
  8. var messenger = new Messenger();
  9. messenger.start();

The TypeScript compiler applies this type of transformation to rewrite arrow function expressions into standard function expressions.

A construct of the form

  1. < T > ( ... ) => { ... }

could be parsed as an arrow function expression with a type parameter or a type assertion applied to an arrow function with no type parameter. It is resolved as the former, but parentheses can be used to select the latter meaning:

  1. < T > ( ( ... ) => { ... } )