4.10 Function Expressions

Function expressions are extended from JavaScript to optionally include parameter and return type annotations.

  FunctionExpression: ( Modified )   functionBindingIdentifieroptCallSignature{FunctionBody}

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

The type of a function expression is an object type containing a single call signature with parameter and return types inferred from the function expression’s signature and body.

When a function expression with no type parameters and no parameter type annotations is contextually typed (section 4.23) by a type T and a contextual signature S can be extracted from T, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in S. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than S, the additional parameters in S are ignored. If the function expression has more parameters than S, the additional parameters are all considered to have type Any.

Likewise, when a function expression with 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, expressions in contained return statements (section 5.10) are contextually typed by the return type of S.

A contextual signature S is extracted from a function type T as follows:

  • If T is a function type with exactly one call signature, and if that call signature is non-generic, S is that signature.
  • If T is a union type, let U be the set of element types in T that have call signatures. If each type in U has exactly one call signature and that call signature is non-generic, and if all of the signatures are identical ignoring return types, then S is a signature with the same parameters and a union of the return types.
  • Otherwise, no contextual signature can be extracted from T.

In the example

  1. var f: (s: string) => string = function (s) {
  2. return s.toLowerCase();
  3. };

the function expression is contextually typed by the type of ‘f’, and since the function expression has no type parameters or type annotations its parameter type information is extracted from the contextual type, thus inferring the type of ‘s’ to be the String primitive type.