Introduction
Some functions do not care about the type of their data: taking the first item of a list, pairing two values, finding the longest of two things. Typing them as any would throw away what the caller knows. Generics keep it: a function gets a type parameter, a placeholder for a type, and each call fills it in. first([3, 1, 2]) returns a number, first(["a"]) a string, and the checker knows which.
How it works
Type parameters are written in angle brackets before the parameter list, and can be used in the parameters and the return type:
function first<T>(items: T[]): T | undefined {
return items[0];
}
At each call, TypeScript infers the type argument from the values: in first([3, 1, 2]), T is number. You can also write it, as in first<string>([]), which is useful when there is nothing to infer from. A function can have several type parameters: pair<A, B>(a: A, b: B): [A, B] keeps both types.
Inside a generic function, TypeScript knows nothing about T, so it allows only what works for every type. To use a property, add a constraint: T extends { length: number } means "any type that has a numeric length", such as strings and arrays. The body may then read a.length, and a call with a number is an error.
A common constraint is keyof. In getProperty<T, K extends keyof T>(obj: T, key: K): T[K], K must be one of T's property names, and the return type T[K], an indexed access type, is the type of that property. So getProperty(book, "pages") is a number, getProperty(book, "title") a string, and getProperty(book, "author") an error.
Generics are everywhere in the standard library: Array<T>, Promise<T>, Map<K, V>, and methods such as map, whose type parameter is the type your callback returns.
Example
// Generic functions: one function, checked for every type it is used with.
function first<T>(items: T[]): T | undefined {
return items[0];
}
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const n = first([3, 1, 2]); // T is number
const s = first<string>([]); // T given explicitly
const p = pair("age", 36); // [string, number]
console.log(n, s, p);
console.log(longest("apple", "fig"), longest([1, 2], [3, 4, 5]));
const book = { title: "Dune", pages: 412 };
console.log(getProperty(book, "pages"), getProperty(book, "title"));Line by line
firstreturnsT | undefined: the item type, or undefined for an empty list.pairkeeps both types in a tuple.longestaccepts anything with alength, and returns the same type it was given.getPropertyaccepts only real keys of the object, and returns that key's type.first<string>([])givesundefined, but its type is still known to bestring | undefined.
Expected result
3 undefined [ 'age', 36 ]
apple [ 3, 4, 5 ]
412 Dune
In the real world
Utility libraries such as Lodash are typed with generics, so groupBy, uniq and sortBy return arrays of your own types. Data-fetching hooks return Promise<T> or a result of T where the caller says what T is. Generic helper functions are often the first thing a team writes once it adopts TypeScript, replacing copies of the same function for different types.
Common mistakes
- Using any instead of a type parameter, which loses the connection between input and output.
- Adding type parameters that are used only once:
function f<T>(x: T): voidgains nothing overunknown. - Using a property of T without a constraint: TypeScript cannot know T has it.
- Writing type arguments that could be inferred, which adds noise.
Best practices
- Use a type parameter when it links two or more places: a parameter and the return type, or two parameters.
- Constrain type parameters as little as possible, but as much as the body needs.
- Name type parameters T, U, K and V for simple cases, and descriptive names such as TItem for complex ones.
Summary
Generic functions have type parameters, filled in by inference or explicitly at each call, so that one function works for many types while the checker keeps track of each. Constraints with extends let the body use particular properties, and K extends keyof T with T[K] types property access exactly.
Quick check
Key takeaways
- A type parameter links the types of inputs and outputs, so the result keeps the caller's type.
- TypeScript usually infers type arguments from the values passed.
- Constraints such as T extends { length: number } let the body use those properties.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.