Code that works for any type, without forgetting which
The last lesson ended with a problem. A helper like once works for any function, and so its parameter can't name one specific function type; but typing it with any loses every bit of information, and the result is unchecked. The same problem appears whenever code is reusable: a function that returns the first element of any array, a stack of any kind of item, a cache, a retry wrapper, an event emitter.
Generics solve it. A generic function has type parameters, placeholders such as T that stand for "whatever type the caller uses". The caller doesn't usually write them: TypeScript infers them from the arguments, and then the return type follows. first([3, 1, 4]) is known to return a number, first(["Ana"]) a string, from one definition. Every collection in the standard library is generic, Array<T>, Map<K, V>, Promise<T>, which is why map, get and await have known types. This lesson shows how to write your own.
Generic functions
Definition— type parameter
A type parameter, declared in angle brackets after a function's name (function first<T>(...)) or a type's name (interface Page<T>), is a variable that ranges over types. Each use of the function or type supplies a type argument for it, written explicitly (first<number>(...)) or, for functions, usually inferred from the arguments.
// Generic functions: type parameters capture the relationship between inputs and outputs.
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const n = first([3, 1, 4]); // number | undefined
const s = first(["Ana", "Bo"]); // string | undefined
console.log(n?.toFixed(1), s?.toUpperCase());
// The `once` helper, now typed properly: the wrapper has exactly the wrapped function's type.
function once<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R {
let done = false;
let result: R;
return (...args: Args): R => {
if (!done) {
done = true;
result = fn(...args);
}
return result;
};
}
const connect = once((host: string, port: number) => `connected to ${host}:${port}`);
console.log(connect("db.local", 5432));
console.log(connect("elsewhere", 1)); // same answer: runs only once
// groupBy for any element type and any key.
function groupBy<T, K extends PropertyKey>(items: readonly T[], keyOf: (item: T) => K): Record<K, T[]> {
const groups = {} as Record<K, T[]>;
for (const item of items) {
const key = keyOf(item);
(groups[key] ??= []).push(item);
}
return groups;
}
const rivers = [
{ name: "Niger", continent: "Africa" as const, km: 4180 },
{ name: "Volga", continent: "Europe" as const, km: 3531 },
{ name: "Congo", continent: "Africa" as const, km: 4700 },
];
const byContinent = groupBy(rivers, (r) => r.continent); // Record<"Africa" | "Europe", ...>
console.log(byContinent.Africa.map((r) => r.name), byContinent.Europe.length);
// Explicit type arguments, when inference has nothing to go on.
const ids = new Set<string>();
ids.add("u-1");
console.log(ids.size, first<number>([]));
export {};3.0 ANA
connected to db.local:5432
connected to db.local:5432
[ 'Niger', 'Congo' ] 1
1 undefinedfirst<T>: the parameteritems: readonly T[]tiesTto the element type of whatever array is passed, and the return typeT | undefinedreuses it. From[3, 1, 4], TypeScript infersT = number.oncehas two type parameters:Args, the tuple of the wrapped function's parameter types, andR, its return type. The wrapper's type(...args: Args) => Ris therefore exactly the wrapped function's type:connecttakes(host: string, port: number)and returns a string, and calling it with wrong arguments is an error. The constraintArgs extends unknown[]saysArgsmust be some array (tuple) type, which a rest parameter requires. This is how utility libraries type their higher-order functions.groupByworks for any element typeTand any key typeK(constrained toPropertyKey, the built-in alias forstring | number | symbol). Because the callback returns a literal"Africa" | "Europe"here, the result is a record with exactly those keys. (ECMAScript 2024 added a built-inObject.groupBy, which TypeScript'ses2024library types almost the same way, except that it returnsPartial<Record<K, T[]>>, honestly admitting that some keys may have no group. This simpler version trusts every key to appear. This course's checks compile against thees2023library, so the program writes its own.)- Arrow functions can be generic too:
const firstOf = <T>(items: readonly T[]): T | undefined => items[0];. In.tsxfiles, where<T>could be mistaken for a JSX tag, the convention is to write<T,>with a trailing comma. - Explicit type arguments are needed when nothing can be inferred:
new Set<string>()creates an empty set that will hold strings, andfirst<number>([])says what the empty array would have contained.
Generics are TypeScript's version of parametric polymorphism, one of the central ideas of type theory (Lumenary Math's type theory): a function that behaves the same way for every type, and whose type says so.
Constraints, keyof and indexed access
An unconstrained T could be anything, so you can do almost nothing with it: not read a property, not call a method. A constraint, T extends Something, limits which types may be used, and in return lets the function use what Something guarantees.
// Constraints: "T can be anything that has...", and keyof for property names.
function longest<T extends { length: number }>(a: T, b: T): T {
return b.length > a.length ? b : a;
}
console.log(longest("kiwi", "papaya"), longest([1, 2], [3]));
// keyof T is the union of T's property names; T[K] is the type of property K.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
interface Country {
name: string;
capital: string;
population: number;
landlocked: boolean;
}
const nepal: Country = { name: "Nepal", capital: "Kathmandu", population: 30_500_000, landlocked: true };
const capital = getProperty(nepal, "capital"); // string
const people = getProperty(nepal, "population"); // number
console.log(capital.toUpperCase(), (people / 1e6).toFixed(1));
// A reusable, type-safe sort by any key.
function sortBy<T, K extends keyof T>(items: readonly T[], key: K, direction: "asc" | "desc" = "asc"): T[] {
const sign = direction === "asc" ? 1 : -1;
return [...items].sort((a, b) => (a[key] < b[key] ? -sign : a[key] > b[key] ? sign : 0));
}
const countries: Country[] = [
nepal,
{ name: "Chile", capital: "Santiago", population: 19_600_000, landlocked: false },
{ name: "Bolivia", capital: "Sucre", population: 12_400_000, landlocked: true },
];
console.log(sortBy(countries, "population").map((c) => c.name).join(" < "));
console.log(sortBy(countries, "name", "desc").map((c) => c.name).join(", "));
// pluck: the result type follows the key.
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const flags: boolean[] = pluck(countries, "landlocked");
console.log(flags);
export {};papaya [ 1, 2 ]
KATHMANDU 30.5
Bolivia < Chile < Nepal
Nepal, Chile, Bolivia
[ true, false, true ]T extends { length: number }accepts strings, arrays and anything else with a numericlength, and preserves which:longest("kiwi", "papaya")returns astring, not a vague "something with a length".keyof Tis the union ofT's property names: forCountry,"name" | "capital" | "population" | "landlocked".T[K], an indexed access type, is the type of propertyK. Together, ingetProperty<T, K extends keyof T>, they make the return type depend on which key is passed:"capital"gives astring,"population"anumber. A misspelled key is caught:getProperty(nepal, "mayor")fails withArgument of type '"mayor"' is not assignable to parameter of type 'keyof Country'.sortByandpluckuse the same pattern for real utilities.pluck(countries, "landlocked")returnsboolean[]becauseCountry["landlocked"]isboolean. (sortBycompares with<and>, which TypeScript allows for anyT[K]; with a key whose values are objects, the comparison would be meaningless, so a production version would constrain the key to properties holding strings or numbers, a technique lesson eight makes possible.)
These patterns are everywhere in typed libraries: an ORM's select("name", "email"), a form library's register("email"), a state store's get("user"), all checked against the property names of your own types.
Generic types and classes
Interfaces, type aliases and classes take type parameters too:
// Generic types and classes: containers that remember what they contain.
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
interface Page<T> {
items: T[];
page: number;
totalPages: number;
}
class Stack<T> {
#items: T[] = [];
push(item: T): this {
this.#items.push(item);
return this;
}
pop(): T | undefined {
return this.#items.pop();
}
peek(): T | undefined {
return this.#items.at(-1);
}
get size(): number {
return this.#items.length;
}
}
const undo = new Stack<string>().push("type 'a'").push("type 'b'").push("delete");
console.log(undo.pop(), undo.peek(), undo.size);
// A typed event emitter: each event name has its own payload type.
type Listener<P> = (payload: P) => void;
class Emitter<Events extends Record<string, unknown>> {
#listeners: { [E in keyof Events]?: Listener<Events[E]>[] } = {};
on<E extends keyof Events>(event: E, listener: Listener<Events[E]>): void {
(this.#listeners[event] ??= []).push(listener);
}
emit<E extends keyof Events>(event: E, payload: Events[E]): void {
for (const listener of this.#listeners[event] ?? []) listener(payload);
}
}
type ShopEvents = {
added: { sku: string; qty: number };
checkout: { totalCents: number };
};
const shop = new Emitter<ShopEvents>();
shop.on("added", ({ sku, qty }) => console.log(`added ${qty} x ${sku}`));
shop.on("checkout", ({ totalCents }) => console.log(`paid ${(totalCents / 100).toFixed(2)}`));
shop.emit("added", { sku: "tea", qty: 2 });
shop.emit("checkout", { totalCents: 900 });
// Generic types compose: a page of results, each of which may have failed.
const page: Page<Result<number, string>> = {
items: [{ ok: true, value: 3 }, { ok: false, error: "timeout" }, { ok: true, value: 4 }],
page: 1,
totalPages: 5,
};
const sum = page.items.reduce((acc, r) => (r.ok ? acc + r.value : acc), 0);
console.log(`page ${page.page}/${page.totalPages}: sum ${sum}`);
export {};delete type 'b' 2
added 2 x tea
paid 9.00
page 1/5: sum 7Result<T, E = Error>has a default type argument:Result<number>meansResult<number, Error>.Page<T>describes a page of any kind of item. Generic types compose:Page<Result<number, string>>is a page of results that each hold a number or an error message.Stack<T>is a generic class:new Stack<string>()creates a stack whosepushaccepts only strings and whosepopreturnsstring | undefined. Returningthisfrompushallows the chained calls.Emitter<Events>is the typed event emitter that libraries commonly offer.Eventsmaps each event name to its payload type, and bothonandemitare generic in the event nameE, so each listener receives exactly the right payload, and a misspelled event or a wrong payload is rejected. In a test file, callingshop.emit("added", { sku: "tea", qty: "two" })andshop.emit("refund", { totalCents: 100 })gives:
main.ts(11,34): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(12,11): error TS2345: Argument of type '"refund"' is not assignable to parameter of type 'keyof ShopEvents'.The field #listeners uses a mapped type, { [E in keyof Events]?: Listener<Events[E]>[] }, which builds an object type with one optional property per event; lesson eight is about mapped types.
One detail in this program trips up many people. ShopEvents is declared with type, not interface, because the emitter's constraint is Record<string, unknown>. An object type written as an alias is considered to fit an index signature; an interface is not, since interfaces can be extended later by declaration merging. Declare ShopEvents as an interface with the same two members, and new Emitter<ShopEvents>() is rejected:
main.ts(12,29): error TS2344: Type 'ShopEvents' does not satisfy the constraint 'Record<string, unknown>'.
Index signature for type 'string' is missing in type 'ShopEvents'.The alternatives are to constrain with object instead, or to use an alias, as here.
Controlling inference: const type parameters and NoInfer
Inference usually guesses right. Two newer features handle the cases where it doesn't.
// const type parameters (TypeScript 5.0): infer literal types without `as const` at each call.
function defineRoutes<const T extends readonly string[]>(paths: T): T {
return paths;
}
const routes = defineRoutes(["/", "/about", "/contact"]); // readonly ["/", "/about", "/contact"]
type Route = (typeof routes)[number]; // "/" | "/about" | "/contact"
function navigate(to: Route): string {
return `navigating to ${to}`;
}
console.log(navigate("/about"), routes.length);
// NoInfer (TypeScript 5.4): stop a parameter from widening what T is inferred to be.
function createSelect<T extends string>(options: readonly T[], initial: NoInfer<T>) {
return { options, value: initial };
}
const size = createSelect(["S", "M", "L"], "M"); // T is "S" | "M" | "L"
console.log(size.value, size.options.join("/"));
export {};navigating to /about 3
M S/M/Lconst type parameters (TypeScript 5.0) ask the compiler to infer the narrowest type for an argument, as if the caller had written as const. Without const, defineRoutes(["/", "/about"]) would infer T as string[], and Route would be plain string; with it, the literal paths survive, and navigate("/abuot") becomes an error.
NoInfer<T> (TypeScript 5.4) marks a use of T that should not contribute to inferring it. In createSelect, T should come only from the options; the initial value should be checked against them. Without NoInfer, TypeScript happily infers T from both arguments, and createSelect(["S", "M", "L"], "XL") compiles, with T widened to "S" | "M" | "L" | "XL". With it:
main.ts(4,31): error TS2345: Argument of type '"XL"' is not assignable to parameter of type '"S" | "M" | "L"'.Reading generic signatures
Much of the generic code you meet will be someone else's: the standard library, a framework, a utility package. Hover over map on an array in your editor and you will see something like map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]. Read it the way the compiler does:
- Which type parameters belong to whom?
Tis the array's own element type, fixed when the array was created (Array<T>).Ubelongs tomapitself and is chosen per call. - Where is each parameter inferred from?
Uappears in the callback's return type, so it is inferred from what your callback returns. - Where does it flow?
Ureappears in the result,U[]. So[1, 2].map((n) => String(n))is astring[].
The same three questions unlock nearly any signature: Promise.all, whose type parameter is a tuple of the promises you pass, so await Promise.all([fetchUser(), fetchOrders()]) gives a correctly typed pair; React's useState<S>(initial: S | (() => S)): [S, Dispatch<SetStateAction<S>>], whose S comes from the initial value; a validation library's parse methods, whose result type comes from the schema object you built. When a signature is too dense to read, look at what the editor shows for a concrete call: the hover over the call displays the type arguments that were inferred, which is often all you need.
When inference picks something too wide or too narrow at a call, you can always pass the type argument explicitly: useState<string | null>(null) says the state will later hold strings, which inference from null alone could never know.
Writing generics others can read
Generic code is powerful, and it is also the easiest TypeScript to make unreadable. The habits that experienced developers follow:
- A type parameter should relate two things. If
Tappears only once in a signature, it is doing nothing that a plain type couldn't:function size<T extends unknown[]>(xs: T): numberis justfunction size(xs: unknown[]): number. The handbook's guidelines for generic functions make the same point: a type parameter that shows up in only one place is almost always unnecessary. - Push type parameters down, keep them few. Prefer
function first<T>(items: T[]): Ttofunction first<A extends any[]>(items: A): A[number]: both work, but the first reads like what it does, and the compiler infers it more predictably. - Use constraints instead of casts. If the body needs
item.id, sayT extends { id: string }; don't cast inside. - Name parameters when there are several. Single letters are conventional for one or two (
T,K,V); beyond that,TEvent,TPayloador plain descriptive names (Events,Args, as above) help. - Don't return a type parameter you can't produce.
function parse<T>(json: string): T { return JSON.parse(json); }looks generic, but it is a type assertion in disguise: the caller picksT, and nothing checks it. Returnunknownand validate, as lesson nine does. - Let inference work. Writing explicit type arguments at every call is noise; if inference keeps getting them wrong, the signature probably needs restructuring.
Common misconceptions
Misconception
"Generics exist at run time, as in C# or Java." They are erased like all types. Inside a generic function you cannot ask what T is: there is no typeof T. If behaviour must depend on the type, pass a value (a key, a parser function, a class) that carries the information.
Misconception
"T extends string means T is string." It means T is some type assignable to string: string itself, or a literal like "S", or a union of literals. That is exactly why createSelect can infer "S" | "M" | "L".
Misconception
"any is just as good as a type parameter." any accepts everything and remembers nothing. A type parameter accepts everything and remembers which thing, so that the output type can follow the input.
Misconception
"keyof T is a list of strings." It is a union type of property names, which may include numbers and symbols (keyof of an array type includes number). Use Extract<keyof T, string> (lesson eight) when only string keys will do.
Exercises
For type questions, ask what each type parameter is inferred to be at the call, then substitute.
1. Generics
Warm-upComputationalWith function first<T>(items: readonly T[]): T | undefined, what is the type of first(["a", "b"])?
2. Generics
CoreComputationalUsing the lesson's generic once, what does this print?
let calls = 0;
const square = once((x: number) => {
calls++;
return x * x;
});
console.log(square(3), square(4), calls);
3. Generics
CoreComputationalWith
interface Country {
name: string;
capital: string;
population: number;
landlocked: boolean;
}
which string literal types make up keyof Country? List them (without quotes is fine).
4. Generics
CoreComputationalWith function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] and the Country interface above, what is the type of pluck(countries, "population")?
5. Generics
Warm-upComputationalWhat does tsc say about getProperty(nepal, "mayor"), where getProperty<T, K extends keyof T>(obj: T, key: K): T[K] and nepal is a Country?
6. Generics
CoreComputationalUsing the lesson's Stack<T> (with push returning this), what does this print?
const s = new Stack<number>().push(1).push(2).push(3);
const top = s.pop();
s.push(4);
console.log(top, s.size);
7. Generics
StretchHumanWhich of these signatures uses a type parameter that adds nothing and should be simplified?
Further reading and resources
- TypeScript Handbook: Generics · Microsoft
- TypeScript Handbook: Keyof type operator · Microsoft
- TypeScript Handbook: More on functions (guidelines for writing good generic functions) · Microsoft
- TypeScript 5.0 release notes: const type parameters · Microsoft
- TypeScript 5.4 release notes: the NoInfer utility type · Microsoft