Generics
A generic is a type parameter: a placeholder you fill in later with a real type. One function or type can then work on many types without falling back to any.
Detailed Explanation
Without generics, a function that returns its argument has a bad choice to make. Type it as (value: any) => any and you lose every check on the result. Type it as (value: string) => string and you cannot pass a number. The third option is to write the function once for every type you care about.
A generic parameter names the missing type and keeps it consistent across the signature:
function identity<T>(value: T): T {
return value;
}
T is not a value. It is a hole in the type. At each call site the compiler fills the hole, usually by looking at the argument. identity("ok") makes T the literal "ok" (or string, depending on context). identity(1) makes T 1. The return type is whatever went in, which is the whole point.
Generics appear on functions, types, interfaces, classes, and methods. The parameter list goes in angle brackets, just after the name: type Box<T> = { value: T }, class Queue<T> { ... }, function map<T, U>(...). Multiple parameters are normal. Map<K, V> is two holes, a key type and a value type.
Inference is what makes generics usable. You rarely write identity<string>("ok"). You write identity("ok") and the compiler solves for T. Inference reads arguments, contextual types (the type expected by the surrounding assignment), and return clauses. When it cannot solve a parameter, you get an implicit unknown or an error under strict — not a silent any, as of recent TypeScript versions.
Two rules keep generic code honest. First, inside the function you only know what the constraint tells you. An unconstrained T has no methods. You cannot call .toUpperCase() on it, because T might be a number. Second, you cannot invent a T. function empty<T>(): T { return {} as T; } compiles only with an assertion, and it is a lie: the caller asked for a User and you handed them an empty object.
The cost is syntax and error messages. A generic with four parameters and two constraints produces diagnostics that name all of them. The benefit is that libraries — Array, Promise, Map, and every typed API you use — share one implementation across every element type without giving up checking.
Code Examples
1. The return type follows the argument.
// 1. The return type follows the argument.
function wrap<T>(value: T): { value: T } {
return { value };
}
const a = wrap("ready"); // { value: string }
const b = wrap(42); // { value: number }
console.log(a.value.toUpperCase()); // "READY"2. Two parameters: transform an array without losing the element type.
// 2. Two parameters: transform an array without losing the element type.
function mapArray<T, U>(items: readonly T[], fn: (item: T) => U): U[] {
const out: U[] = [];
for (const item of items) {
out.push(fn(item));
}
return out;
}
const lengths = mapArray(["ada", "grace"], (name) => name.length);
// lengths is number[]3. A generic type alias, and why you cannot assume methods on T.
// 3. A generic type alias, and why you cannot assume methods on T.
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function first<T>(items: readonly T[]): Result<T, "empty"> {
if (items.length === 0) {
return { ok: false, error: "empty" };
}
return { ok: true, value: items[0] };
// items[0].toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'T'.
}Common Gotchas
Unconstrained `T` has no members
the compiler will not let you read `.id` or call `.map` until you constrain `T` or narrow a value of type `T` at runtime.
Do not assert your way to a `T`
`return {} as T` compiles and then explodes at the call site. Construct a real `T`, or change the return type.
Inference reads the first use, not your hope
if a parameter is used as both `T` and `T[]`, a mismatch produces an error on the argument that did not fit, which can look like the wrong line.
Default `T = any` reintroduces `any`
a default of `unknown` or a useful constraint is safer. See default type parameters.