6.5 Generic Functions

A function implementation may include type parameters in its signature (section 3.9.2.1) and is then called a generic function. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct.

Type parameters declared in the signature of a function implementation are in scope in the signature and body of that function implementation.

The following is an example of a generic function:

  1. interface Comparable {
  2. localeCompare(other: any): number;
  3. }
  4. function compare<T extends Comparable>(x: T, y: T): number {
  5. if (x == null) return y == null ? 0 : -1;
  6. if (y == null) return 1;
  7. return x.localeCompare(y);
  8. }

Note that the ‘x’ and ‘y’ parameters are known to be subtypes of the constraint ‘Comparable’ and therefore have a ‘compareTo’ member. This is described further in section 3.6.1.

The type arguments of a call to a generic function may be explicitly specified in a call operation or may, when possible, be inferred (section 4.15.2) from the types of the regular arguments in the call. In the example

  1. class Person {
  2. name: string;
  3. localeCompare(other: Person) {
  4. return compare(this.name, other.name);
  5. }
  6. }

the type argument to ‘compare’ is automatically inferred to be the String type because the two arguments are strings.