Sub topic 9
Generic functions
This chapter assumes you can annotate parameters and return types, write function type expressions, and read union types. It builds on the earlier chapters on function types and callbacks. The next chapter covers constraints in depth, so here they appear only where they explain an error.
Why generics exist
Suppose you write a function that returns the first element of an array. You have two choices without generics, and both are poor.
function firstNumber(items: number[]): number | undefined {
return items[0];
}
function firstAny(items: any[]): any {
return items[0];
}The first version works for numbers only. The second accepts any array, but the caller loses all type information about the result. A generic function solves this with a type parameter, a placeholder for a type that is filled in on each call.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const a = first([1, 2, 3]); // number | undefined
const b = first(["x", "y"]); // string | undefined
const c = first<boolean>([]); // boolean | undefined<T> after the function name declares the type parameter. T can then appear in parameter types, the return type and the body. The name is a convention. Longer names such as TItem are fine when a function has several parameters.
How inference picks T
You rarely write the type argument yourself. At each call the compiler compares the argument types with the parameter types and collects candidates for each type parameter. It then chooses one type for each parameter and substitutes it everywhere in the signature.
The compiler infers T once per call, not once per function. Two calls to the same function can resolve T to different types, as the first calls above show.
Several type parameters
Use one type parameter for each type that varies independently. A map function has an input element type and an output element type.
function mapItems<T, U>(items: T[], transform: (item: T) => U): U[] {
const result: U[] = [];
for (const item of items) {
result.push(transform(item));
}
return result;
}
const lengths = mapItems(["a", "bb", "ccc"], s => s.length); // number[]Inference happens in order here. The compiler reads T from the first argument, which gives string. It then uses that to type the parameter s in the arrow function, which is contextual typing. The callback returns number, so U becomes number. This is why the array argument should come before the callback in the parameter list. If the callback came first, s would have no type to be inferred from.
Explicit type arguments
You can pass type arguments in angle brackets when inference has nothing to work with or picks the wrong type.
const none = first<string>([]); // string | undefined
const loose = first([]); // never | undefined, which is just undefinedAn empty array literal gives no useful candidate, so T becomes never. Writing first<string>([]) fixes that.
If you supply type arguments, you must supply all of them, unless the omitted ones have defaults. TypeScript does not support partial inference. mapItems<string>(...) is an error because U is missing.
Default type parameters
A type parameter can have a default. The default is used when the call gives the compiler no candidates and you pass no explicit type.
function emptyList<T = string>(): T[] {
return [];
}
const names = emptyList(); // string[]
const ids = emptyList<number>(); // number[]Without the default, emptyList() would return unknown[].
Conflicting candidates
When one type parameter appears in several parameters, each argument adds a candidate. If the candidates cannot be reconciled, the call fails.
function pair<T>(a: T, b: T): [T, T] {
return [a, b];
}
// pair(1, "x");
// error: Argument of type 'string' is not assignable to parameter of type 'number'.
const mixed = pair<string | number>(1, "x"); // [string | number, string | number]The compiler fixes T as number from the first argument, so the second argument is rejected. Passing the union explicitly resolves it. If you want each argument to keep its own type, use two type parameters (<A, B>) and return [A, B].
Generic function types
Generics also apply to function types, and where you place the type parameter changes the meaning.
// The type parameters belong to the call: each call picks its own T and U.
type Mapper = <T, U>(items: T[], transform: (item: T) => U) => U[];
const mapper: Mapper = mapItems;
const upper = mapper(["a", "b"], s => s.toUpperCase()); // string[]
// The type parameter belongs to the alias: T is fixed when you write the type.
type Transform<T> = (value: T) => T;
const double: Transform<number> = n => n * 2;A Mapper value works for any element types. A Transform<number> works for numbers only, because T was fixed when the type was written. Choose the first form when the function itself must be generic, and the second when a type needs to be configured once.
The same distinction applies to call signatures in object types. { <T>(x: T): T } describes a generic function, while { (x: T): T } inside interface Foo<T> describes a function whose T is chosen by whoever uses Foo.
Generic arrow functions
Arrow functions take type parameters before the parameter list.
const last = <T>(items: T[]): T | undefined => items[items.length - 1];In a .tsx file, <T> looks like a JSX tag and the parser rejects it. Add a trailing comma, or a constraint, to disambiguate:
const lastTsx = <T,>(items: T[]): T | undefined => items[items.length - 1];
const lastTsx2 = <T extends unknown>(items: T[]): T | undefined => items[items.length - 1];What you can do with an unconstrained T
Inside the body, an unconstrained T is opaque. The compiler knows nothing about it, so you can only pass it around, store it, or return it.
// function getLength<T>(value: T): number {
// return value.length; // error: Property 'length' does not exist on type 'T'.
// }The fix is a constraint such as T extends { length: number }, which the next chapter covers.
Common mistakes
| Mistake | What happens | Better approach |
|---|---|---|
| Type parameter used only once | It adds no relationship between types, only noise | Use the plain type, for example `items: unknown[]` instead of `<T extends unknown[]>(items: T)` when `T` is not reused |
| Type parameter only in the return type | The caller asserts a type the compiler cannot check | Return `unknown` and narrow, or validate the data |
| Passing only some type arguments | Error: expected N type arguments | Pass all of them, or give the rest defaults |
| Callback listed before the array it depends on | Callback parameters cannot be inferred | Put the source argument first |
| Using `any` instead of a type parameter | Input and output types are no longer linked | Use `T` so the result follows the argument |
The second row deserves a closer look.
function parse<T>(json: string): T {
return JSON.parse(json); // compiles, but nothing checks that the data is a T
}
const user = parse<{ name: string }>("42"); // no error, wrong at runtimeGenerics are erased
Type parameters exist only at compile time. The emitted JavaScript for first has no trace of T, so you cannot write new T() or typeof T inside the function. If you need runtime behavior that depends on the type, pass a value, such as a constructor or a factory function, as an argument.
Exercise
Given mapItems from this chapter, what type does const r = mapItems([1, 2, 3], n => String(n)); have, and how does the compiler arrive at it?
Show answer
r is string[]. The compiler infers T as number from the array argument. That types n as number in the callback. The callback returns string, so U is string, and the return type U[] becomes string[].
Exercise
Why does pair(1, "x") fail for function pair<T>(a: T, b: T): [T, T], and what are two ways to make the call compile?
Show answer
T is inferred as number from the first argument, so the string "x" is not assignable. One fix is to pass a union explicitly: pair<string | number>(1, "x"). The other is to give each parameter its own type parameter: function pair<A, B>(a: A, b: B): [A, B].