1.2 Function Types
Function expressions are a powerful feature of JavaScript. They enable function definitions to create closures: functions that capture information from the lexical scope surrounding the function’s definition. Closures are currently JavaScript’s only way of enforcing data encapsulation. By capturing and using environment variables, a closure can retain information that cannot be accessed from outside the closure. JavaScript programmers often use closures to express event handlers and other asynchronous callbacks, in which another software component, such as the DOM, will call back into JavaScript through a handler function.
TypeScript function types make it possible for programmers to express the expected signature of a function. A function signature is a sequence of parameter types plus a return type. The following example uses function types to express the callback signature requirements of an asynchronous voting mechanism.
function vote(candidate: string, callback: (result: string) => any) {
// ...
}
vote("BigPig",
function(result: string) {
if (result === "BigPig") {
// ...
}
}
);
In this example, the second parameter to ‘vote’ has the function type
(result: string) => any
which means the second parameter is a function returning type ‘any’ that has a single parameter of type ‘string’ named ‘result’.
Section 3.9.2 provides additional information about function types.