5.10 Return Statements

It is an error for a ‘return’ statement to occur outside a function body. Specifically, ‘return’ statements are not permitted at the global level or in namespace bodies.

A ‘return’ statement without an expression returns the value ‘undefined’ and is permitted in the body of any function, regardless of the return type of the function.

When a ‘return’ statement includes an expression, if the containing function includes a return type annotation, the return expression is contextually typed (section 4.23) by that return type and must be of a type that is assignable to the return type. Otherwise, if the containing function is contextually typed by a type T, Expr is contextually typed by T‘s return type.

In a function implementation without a return type annotation, the return type is inferred from the ‘return’ statements in the function body, as described in section 6.3.

In the example

  1. function f(): (x: string) => number {
  2. return s => s.length;
  3. }

the arrow expression in the ‘return’ statement is contextually typed by the return type of ‘f’, thus giving type ‘string’ to ‘s’.