Generics — TypeScript

A generic uses a type parameter like <T> (like a variable that holds a type), so one function works for many types, and TypeScript still knows the result's…

You want one function, last, that takes the last item from any array: numbers, text, booleans. If the parameter is typed number[], an array of text is refused. If it's typed any[], everything gets in, but the result's type becomes any too, so TypeScript no longer knows what type comes out.

A generic is the middle way: one function (or one type) that works for many types without losing the type information. You do it with a type parameter, usually called T. A type parameter is like a variable, except it holds a type, and that type is decided each time the function is called. Think of a cloakroom: the attendant doesn't care whether you leave a helmet or an umbrella, but what you pick up is always the very thing you left. The cloakroom is the generic function. The thing you leave is the argument, with its type T, and the thing you pick up is the return value, with the same type T.

Why not just use any

We want a function that takes the last item of any array. The easiest way is any:

function lastAny(arr: any[]): any {
  return arr[arr.length - 1];
}

const result = lastAny([1, 2, 3]); // result: any
result.toUpperCase(); // TypeScript says nothing

When the program runs, the last line stops with an error:

TypeError: result.toUpperCase is not a function

any disables checking. result is really the number 3, and numbers have no .toUpperCase(), yet TypeScript reports no error. The error only appears when the program runs, while the whole point of TypeScript is to catch errors like this before the program runs.

T follows the argument

This is the generic version of the same function:

function last<T>(arr: T[]): T {
  return arr[arr.length - 1];
}

const a = last([1, 2, 3]);     // T = number, a: number, value 3
const b = last(["a", "b"]);    // T = string, b: string, value "b"
const c = last([true, false]); // T = boolean, c: boolean, value false
Call T Result type Value
last([1, 2, 3]) number number 3
last(["a", "b"]) string string "b"
last([1, "a"]) string | number string | number "a"

So a is a number, and b is a string. Because the types are exact, b.toUpperCase() is allowed, while a.toUpperCase() is refused before it runs:

error TS2339: Property 'toUpperCase' does not exist on type 'number'.

You can also write T yourself: last<string>(["a", "b"]). If the contents don't fit, as in last<string>([1, 2, 3]), each number is refused with Type 'number' is not assignable to type 'string'. (ts(2322)).

Limiting T with extends

Sometimes your function needs something from a value of type T. The function getLength below needs .length:

function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

getLength("word");    // 4
getLength([1, 2, 3]); // 3
getLength(123);       // error

The line getLength(123) is refused:

error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

Generic types

Not just functions. Interfaces and type aliases can have type parameters too:

interface ApiResponse<T> {
  data: T;
  status: number;
}

const res: ApiResponse<string[]> = { data: ["Coffee", "Tea"], status: 200 };

ApiResponse<string[]> fills T with string[], so data must be an array of strings. The shape of ApiResponse is the same for every endpoint (an address on a server that sends data), only the type of data changes. You've actually used generic types many times already: string[] is the same as Array<string>.

⚠️ The any shortcut, and an index that's off by one

TL;DR: A generic uses a type parameter like <T> (like a variable that holds a type), so one function works for many types, and TypeScript still knows the result's type. function last<T>(arr: T[]): T returns the last item of the array (arr[arr.length - 1]), and TypeScript guesses T from the argument: last([1, 2, 3]) is a number, last(["a", "b"]) is a string. Unlike with any, a mistake like .toUpperCase() on a number is caught before the program runs. Limit T with extends: when getLength uses T extends { length: number } (T must have a length), TypeScript refuses getLength(123), because a number has no length. Interfaces can be generic too, like ApiResponse<T>, where T decides the type of the property data.

⚡ any passes, and the error moves to run time

Write:

function lastAny(arr: any[]): any {
  return arr[arr.length - 1];
}

const result = lastAny([1, 2, 3]);
result.toUpperCase();
Guess first: does TypeScript report an error on the last line?

No. any disables checking, so the error only appears while the program runs: TypeError: result.toUpperCase is not a function.

Meaning: result is really the number 3, but because its type is any, TypeScript doesn't know that result is a number.

⚡ T follows the argument

Write:

function last<T>(arr: T[]): T {
  return arr[arr.length - 1];
}

const a = last([1, 2, 3]);  // a: number
const b = last(["a", "b"]); // b: string

Meaning: <T> makes a type parameter, a kind of variable that holds a type. A function with a type parameter is called a generic. TypeScript guesses T from the argument, so a is a number, and a.toUpperCase() is rejected before running. arr.length - 1 is the last index, because indexes start at 0.

⚡ Limit T with extends

Write:

function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

getLength("word"); // 4
getLength(123);    // error

Meaning: T extends { length: number } means T can be any type, as long as it has a length. This limit is called a constraint. Strings and arrays have one, numbers don't, so getLength(123) is rejected.

What you will learn