Why generics, and generic functions
The problem `any` and `unknown` can't solve, and how a type parameter lets one function keep the link between what goes in and what comes out.
Parameter and return typesany, unknown, never, and voidUnion and literal types
Why generics, and generic functions
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Some functions work the same way whatever type they are given, and their return type depends on the argument's type; `any` throws that link away, and `unknown` keeps it safe but useless.
- A type parameter such as `T` in `function first<T>(items: T[]): T | undefined` is a placeholder the compiler fills in fresh at every call, so `first([1, 2])` returns `number | undefined` and `first(["a"])` returns `string | undefined`.
- Callers almost never write the type argument; TypeScript infers it from the arguments, and an explicit `first<string>(...)` is only needed when there is nothing to infer from or the inferred type is wrong.
- A function can take several type parameters, such as `map<T, U>`, when it relates more than one type, like an input element type and an output element type.
- A type parameter earns its place by appearing at least twice, typically in a parameter and the return type; one that appears only in the return type is a type assertion in disguise.
- Generics are a compile-time feature only; the type parameters are erased, and the JavaScript that runs is the same function with no types in it.
A function that doesn’t care what it holds
Some functions do the same job whatever you give them. Returning the first element of an array is the simplest case: the logic is identical for an array of strings, numbers, or users. The question is what type to write.
Your first two options both disappoint:
function firstAny(items: any[]): any {
return items[0];
}
const a = firstAny(["x", "y"]); // any
a.toFixed(2); // compiles, then throws at runtime
function firstUnknown(items: unknown[]): unknown {
return items[0];
}
const b = firstUnknown(["x", "y"]); // unknown
b.toUpperCase(); // Error: 'b' is of type 'unknown'.
any switches the checker off, so a string gets treated as a number without complaint. unknown is safe, but it forgets what you passed in: you handed over strings and got back something you have to narrow before you can use. Writing one copy per type, such as firstString and firstNumber, works but never ends.
The real problem is a missing relationship. The return type depends on the argument type, and neither signature can say so.
Type parameters
A generic function declares a type parameter in angle brackets and then uses it like any other type:
function first<T>(items: T[]): T | undefined {
return items[0];
}
const c = first(["x", "y"]); // string | undefined
const d = first([1, 2, 3]); // number | undefined
Think of T as a parameter that holds a type instead of a value. A normal parameter is filled in with a value at each call; T is filled in with a type at each call. The signature now says exactly what was missing: whatever element type goes in, that same type comes out.
You rarely write T yourself at the call site. TypeScript looks at ["x", "y"], sees string[], and concludes T is string. You can supply it explicitly with first<string>(["x"]), which is useful when there’s nothing to infer from, such as an empty array. Most of the time the arguments say enough. The inference lesson later in this group covers how that works in detail.
The name T is only a convention. Longer names such as TItem read better once a signature has several parameters.
More than one type parameter
A function can relate several types at once. map takes items of one type and a callback that turns each into another:
function map<T, U>(items: T[], fn: (item: T) => U): U[] {
const out: U[] = [];
for (const item of items) out.push(fn(item));
return out;
}
const lengths = map(["a", "bb"], (s) => s.length); // number[]
T is inferred from the array as string, which also gives s its type inside the callback. U is inferred from what the callback returns, number. Neither the array’s type nor the callback’s return type was written anywhere at the call site, and both flow through to the result.
Arrow functions take type parameters too: const identity = <T,>(value: T): T => value;. The trailing comma matters only in .tsx files, where <T> alone would be read as a JSX tag.
When a type parameter is pulling its weight
A type parameter exists to connect two things, usually a parameter and the return type, or two parameters. If it appears only once, it connects nothing:
function parse<T>(json: string): T {
return JSON.parse(json);
}
const user = parse<{ name: string }>('{"nme":"Ada"}'); // { name: string }, but wrong
This looks type-safe, but nothing checks the claim. The caller picks T, and the compiler believes them. It’s a type assertion dressed as a generic, and an honest signature would return unknown and make the caller validate. A useful rule of thumb: if you could delete the type parameter and replace it with its constraint or unknown without losing information, delete it.
What happens at runtime
Nothing. Generics live entirely in the type system. After compilation, first<T> is plain function first(items) { return items[0]; }. That’s why you can’t write if (T === String) inside a generic function: T has no runtime existence. When a function needs to behave differently per type, it has to inspect the value, not the type parameter.
About the video
Kyle Cook’s walkthrough starts from the same place this lesson does: a function that loses type information because it’s typed with any or a union. From there he builds up generic functions step by step, which lines up with the first four sections above. The back half of the video moves into constraints and more advanced features, which are the next lessons in this group. Watch it through for a preview, then return to those topics in their own lessons for the details.
Check yourself
Why is `function first(items: any[]): any` a worse signature than `function first<T>(items: T[]): T | undefined`, even though both accept the same arguments?
With `any`, the result of `first(["a"])` is `any`, so calling `.toFixed()` on it compiles and fails at runtime. The generic version ties the return type to the element type of the argument, so the same call returns `string | undefined` and the compiler rejects the `number` method.
If `unknown` is the safe alternative to `any`, why doesn't `function first(items: unknown[]): unknown` solve the problem?
It is safe but it forgets what the caller passed in. The result is `unknown` even when the caller handed over an array of strings, so they have to narrow or assert a value whose type was never in doubt. A type parameter keeps the specific type instead of collapsing it.
When would you write a type argument explicitly, as in `first<string>([])`?
When inference has nothing useful to work with, such as an empty array literal, or when it would infer something narrower or wider than you want. Most of the time the arguments carry enough information and the explicit form is just noise.
What is wrong with `function parse<T>(json: string): T { return JSON.parse(json); }`?
`T` appears only in the return type, so nothing checks it. The caller picks any type they like with `parse<User>(text)` and the compiler accepts it without looking at the data, which makes it an unchecked type assertion written to look like a safe generic.
Why does `map<T, U>` need two type parameters instead of one?
The input array's elements and the callback's return values are usually different types, such as strings in and numbers out. One parameter would force them to be the same type; two let the signature say that the output array has the type the callback returns.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.