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.

  1. function vote(candidate: string, callback: (result: string) => any) {
  2. // ...
  3. }
  4. vote("BigPig",
  5. function(result: string) {
  6. if (result === "BigPig") {
  7. // ...
  8. }
  9. }
  10. );

In this example, the second parameter to ‘vote’ has the function type

  1. (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.