Show contents
Chapter 4 of 7 · 20 min
Generics
By the end of this chapter, you'll be able to
- Write a generic function with a type parameter
- Constrain a type parameter with extends and keyof
- Type a generic data structure
- Derive new types with Partial, Pick, Omit and Record
A type as a parameter
You declare a type parameter between angle brackets, often named T, then use it like any other type:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([42, 7, 19]);
const city = first(["Lomé", "Accra"]);
console.log(n, city?.toUpperCase());
42 LOMÉ
On each call, TypeScript infers T from the arguments: number for the first, string for the second. city therefore has type string | undefined, and ?. only calls toUpperCase() if the value exists. You have already used generics without knowing it: number[] can also be written Array<number>, and a promise of text is a Promise<string>.
An interface can have a type parameter too:
interface Response<T> {
ok: boolean;
data: T;
}
const r: Response<string[]> = { ok: true, data: ["Dakar", "Thiès"] };
console.log(r.data.length);
2
Constrain a type
Without care, T can be anything: TypeScript therefore refuses access to a property it does not know. extends sets a constraint: T must at least have the given shape.
function mostExpensive<T extends { price: number }>(items: T[]): T {
return items.reduce((max, a) => (a.price > max.price ? a : max));
}
const best = mostExpensive([
{ name: "Tea", price: 1200, origin: "Kenya" },
{ name: "Coffee", price: 3500, origin: "Ethiopia" },
]);
console.log(best.name, best.origin);
Coffee Ethiopia
The result keeps its whole type: best.origin is accessible, although the constraint only mentioned price. This is what sets a generic apart from a plain parameter of type { price: number }.
keyof T is the union of the property names of T. Combined with extends, it guarantees that a key really exists:
function sortBy<T, K extends keyof T>(items: T[], key: K): T[] {
return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));
}
const countries = [
{ name: "Mali", population: 23 },
{ name: "Benin", population: 14 },
{ name: "Niger", population: 27 },
];
console.log(sortBy(countries, "population").map((c) => c.name));
["Benin","Mali","Niger"]
Populations are in millions, rounded. sortBy(countries, "area") would be refused: "area" is not a key of these objects. The lab displays arrays in JSON format.
Each variable received the precise type that matches its call.
Text description of the animation
- First call: the items are numbers, TypeScript infers T = number.
- The function returns the first item. At run time, T no longer exists: this is ordinary JavaScript.
- Second call: this time T = string. n is a number, city will be a string.
- The same code runs with other values.
- Each variable received the precise type that matches its call.
Utility types
TypeScript provides ready-made generics to derive a type from another, instead of rewriting it:
| Type | Result |
|---|---|
Partial<T> | every property becomes optional |
Readonly<T> | every property becomes read-only |
Pick<T, "a" | "b"> | keeps only the listed properties |
Omit<T, "a"> | removes the listed properties |
Record<K, V> | an object whose keys are K and values V |
interface Product {
id: number;
name: string;
price: number;
stock: number;
}
type Update = Partial<Omit<Product, "id">>;
function update(p: Product, changes: Update): Product {
return { ...p, ...changes };
}
const stockByCity: Record<string, number> = { Dakar: 12, Bamako: 4 };
const mango: Product = { id: 7, name: "Mango", price: 300, stock: 50 };
console.log(update(mango, { price: 250 }));
console.log(stockByCity["Bamako"]);
{"id":7,"name":"Mango","price":250,"stock":50}
4
Update accepts any subset of the properties, except id: an update cannot change the identifier. If Product gains a property, Update follows automatically.
Mini-lab: a generic queueTypeScript
Output
Click “Run”: the TypeScript compiler will be loaded in your browser (about 3 MB the first time). Your code is checked, then run if it has no type error.Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: group by category
Write a generic function groupBy(items, key) that returns an object where each key is a value of key and each value is the list of matching items. Test it on products grouped by category.
Hint 1
function groupBy<T, K extends keyof T>(items: T[], key: K): Record<string, T[]>.Hint 2
String(e[key]) turns the key's value into text, usable as a property name.Show the solution and common mistakes
function groupBy<T, K extends keyof T>(items: T[], key: K): Record<string, T[]> {
const groups: Record<string, T[]> = {};
for (const e of items) {
const k = String(e[key]);
(groups[k] ??= []).push(e);
}
return groups;
}
const products = [
{ name: "Mango", category: "fruit" },
{ name: "Okra", category: "vegetable" },
{ name: "Papaya", category: "fruit" },
];
const groups = groupBy(products, "category");
console.log(Object.keys(groups), groups["fruit"]?.length);
["fruit","vegetable"] 2
??= only assigns an empty array if groups[k] does not exist yet. groups["fruit"]?.length: a Record<string, …> does not guarantee that the key "fruit" exists, hence the ?. as a precaution.
Common mistakes:
- Typing
key: string:groupBy(products, "categry")would pass without error and group everything under"undefined". - Returning
Record<K, T[]>: the result's keys are the property's values (“fruit”), not its name (“category”).
Summary
- 1A generic takes a type as a parameter: function first<T>(e: T[]): T | undefined.
- 2TypeScript infers the type parameter on each call, and the result keeps its precise type.
- 3extends constrains a type parameter; keyof T is the property names of T.
- 4Partial, Readonly, Pick, Omit and Record derive one type from another, without rewriting it.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.