1.9 Generic Types and Functions

Like overloading on string parameters, generic types make it easier for TypeScript to accurately capture the behavior of JavaScript libraries. Because they enable type information to flow from client code, through library code, and back into client code, generic types may do more than any other TypeScript feature to support detailed API descriptions.

To illustrate this, let’s take a look at part of the TypeScript interface for the built-in JavaScript array type. You can find this interface in the ‘lib.d.ts’ file that accompanies a TypeScript distribution.

  1. interface Array<T> {
  2. reverse(): T[];
  3. sort(compareFn?: (a: T, b: T) => number): T[];
  4. // ...
  5. }

Interface definitions, like the one above, can have one or more type parameters. In this case the ‘Array’ interface has a single parameter, ‘T’, that defines the element type for the array. The ‘reverse’ method returns an array with the same element type. The sort method takes an optional parameter, ‘compareFn’, whose type is a function that takes two parameters of type ‘T’ and returns a number. Finally, sort returns an array with element type ‘T’.

Functions can also have generic parameters. For example, the array interface contains a ‘map’ method, defined as follows:

  1. map<U>(func: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

The map method, invoked on an array ‘a’ with element type ‘T’, will apply function ‘func’ to each element of ‘a’, returning a value of type ‘U’.

The TypeScript compiler can often infer generic method parameters, making it unnecessary for the programmer to explicitly provide them. In the following example, the compiler infers that parameter ‘U’ of the map method has type ‘string’, because the function passed to map returns a string.

  1. function numberToString(a: number[]) {
  2. var stringArray = a.map(v => v.toString());
  3. return stringArray;
  4. }

The compiler infers in this example that the ‘numberToString’ function returns an array of strings.

In TypeScript, classes can also have type parameters. The following code declares a class that implements a linked list of items of type ‘T’. This code illustrates how programmers can constrain type parameters to extend a specific type. In this case, the items on the list must extend the type ‘NamedItem’. This enables the programmer to implement the ‘log’ function, which logs the name of the item.

  1. interface NamedItem {
  2. name: string;
  3. }
  4. class List<T extends NamedItem> {
  5. next: List<T> = null;
  6. constructor(public item: T) {
  7. }
  8. insertAfter(item: T) {
  9. var temp = this.next;
  10. this.next = new List(item);
  11. this.next.next = temp;
  12. }
  13. log() {
  14. console.log(this.item.name);
  15. }
  16. // ...
  17. }

Section 3.7 provides further information about generic types.