Lesson 10
25 min
Write reusable code that keeps type safety, with T and extends.
Definition
A generic is a "fill-in-the-blank" type: instead of writing a specific type, you use a type parameter (often written T) whose value will be chosen later, at the time of use. The same code can then work with several types, while keeping the safety of each one.
Think of a labeled box: the box itself doesn't change, but the label says what it contains, books, shoes or tools. Generics work the same way: a single definition, several possible contents, and the editor always knows what is inside.
Imagine a function that returns the first element of an array. For it to work with numbers and strings, you could write two versions, or use any and lose type safety. Generics offer a better solution.
function firstNumber(arr: number[]): number {
return arr[0];
}
function firstString(arr: string[]): string {
return arr[0];
}
// Same logic, twice...function firstAny(arr: any[]): any {
return arr[0];
}
const x = firstAny([10, 20]);
x.toUpperCase(); // No error... but it crashes at runtime!The version with any avoids the repetition, but it loses all information: the result no longer has a type, and TypeScript no longer detects the error on the last line. We need a way to say "the result has the same type as the elements of the array", whatever that type is.
A generic is a type parameter, written between angle brackets after the function name. By convention, it is named T (for "Type"). TypeScript automatically determines its value from the arguments.
function first<T>(arr: T[]): T {
return arr[0];
}
const a = first([10, 20, 30]); // a: number
const b = first(["x", "y", "z"]); // b: string
const c = first<boolean>([true]); // type specified by hand
In the first call, TypeScript sees an array of numbers, deduces that T is number, and therefore knows that the result is a number. In the second, T is string. You can also specify T yourself between angle brackets, as in the third call, but inference rarely makes that necessary.
A function can have as many type parameters as needed. They are then named A, B, or with more meaningful names like Key and Value when that helps.
function createPair<A, B>(first: A, second: B): [A, B] {
return [first, second];
}
const pair = createPair("Lea", 25); // [string, number]Arrow functions can also be generic: the angle brackets go right before the parameter parentheses. This notation is very common for small utilities.
const identity = <T>(value: T): T => value;
const n = identity(42); // number
const t = identity("text"); // stringIn a .tsx file (React), <T> would be mistaken for an HTML tag: you then write <T,> instead. In a regular .ts file, as here, the simple form is enough.
Generics also apply to interfaces and classes. A very common case: describing the response of an API whose content varies.
interface ApiResponse<T> {
success: boolean;
data: T;
}
interface User {
name: string;
}
const res1: ApiResponse<User> = {
success: true,
data: { name: "Lea" },
};
const res2: ApiResponse<number[]> = {
success: true,
data: [1, 2, 3],
};class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const stack = new Stack<string>();
stack.push("a");
stack.push(42); // Error: number is not assignable to stringA stack is a structure where the last element added is the first one removed. Thanks to the generic, the same Stack class works for texts, numbers or objects, and each stack stays homogeneous: a Stack<string> rejects anything that isn't a text.
Like function parameters, a type parameter can have a default value, indicated with the equals sign. It is used when no other value is specified.
interface Box<T = string> {
content: T;
}
const b1: Box = { content: "text" }; // T is string
const b2: Box<number> = { content: 42 }; // T is numberSometimes, T can't be just any type: the function needs a specific property. You then limit T with extends.
function printLength<T extends { length: number }>(item: T): number {
return item.length;
}
printLength("hello"); // 5
printLength([1, 2, 3]); // 3
printLength(42); // Error: number has no length propertyThe constraint extends { length: number } means: "T can be any type, as long as it has a length property of type number". Texts and arrays qualify, numbers don't. Inside the function, you can then read item.length safely.
Good to know
You already use generics without knowing it: number[]is a shorthand for Array<number>, andPromise<string> describes a promise that will produce a text.
You can also constrain a type parameter based on another one. The keyof operator produces the union of a type's property names, which lets you write a function that reads a property safely.
function read<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person = { name: "Lea", age: 25 };
const personName = read(person, "name"); // string
const personAge = read(person, "age"); // number
read(person, "email"); // Error: email does not existHere, K can only be "name" or "age", and the return type T[K] automatically adapts to the requested property. A typo in the property name is detected immediately.
T appears only once in the signature, it links nothing and a simple type is enough.any destroys it.Generics are one of TypeScript's most powerful tools, but also one of the most intimidating at first. Don't try to write them everywhere: start by using them (arrays, promises, API responses), then write your own when you notice identical code repeated for several types.
extends limits the accepted types; the equals sign gives a default value.Exercise
last<T>(arr: T[]) that returns the last element of an array (or undefined if the array is empty), and test it with numbers and strings.Going further
Box<T> that stores a value, with the methods get() and replace(value: T).