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
( ... ) => expr
is exactly equivalent to
( ... ) => { return expr ; }
Furthermore, arrow function expressions of the forms
id => { ... }
id => expr
are exactly equivalent to
( id ) => { ... }
( id ) => expr
Thus, the following examples are all equivalent:
(x) => { return Math.sin(x); }
(x) => Math.sin(x)
x => { return Math.sin(x); }
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
class Messenger {
message = "Hello World";
start() {
setTimeout(() => alert(this.message), 3000);
}
};
var messenger = new Messenger();
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:
class Messenger {
message = "Hello World";
start() {
var _this = this;
setTimeout(function() { alert(_this.message); }, 3000);
}
};
var messenger = new Messenger();
messenger.start();
The TypeScript compiler applies this type of transformation to rewrite arrow function expressions into standard function expressions.
A construct of the form
< 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:
< T > ( ( ... ) => { ... } )