Advanced · 7 of 12 · 17 min read
Generics, deeper
How the compiler actually resolves a type parameter — inference sites, constraints, defaults, variance annotations, and the generic signatures that make a library usable.
- Generics
- Generic constraints
A type parameter is an argument the caller usually does not write. Everything that makes generics pleasant — and everything that makes them baffling — follows from how the compiler fills them in.
Watching it resolve
1 The signature declares two parameters. K is constrained by T, so the order they get resolved in is not arbitrary — T has to be known before K can be checked.
2 The call supplies two arguments and no type arguments. Everything from here is the compiler working backwards from the values it was given.
3 items: T[] is matched against User[], so T = User. This is an inference site: a position in the parameter list where a type parameter appears, which is the only place inference can happen.
4 key: K is matched against "name". Normally a string literal would widen to string — it does not here, because K is constrained to keyof T, and a constraint of literal types keeps the literal.
5 Now the constraint is checked: is "name" assignable to keyof User? It is. Had the call passed "nmae", this is the step that would have failed — with inference already complete, which is why the error names the key rather than the array.
6 Both parameters are substituted into the return type. T[K][] becomes User["name"][], which is string[] — and the caller wrote no type arguments at all.
interface User { id: number; name: string; email: string }
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const users: User[] = [{ id: 1, name: "Ana", email: "a@b.c" }];
const names = pluck(users, "name"); // string[]
const ids = pluck(users, "id"); // number[]
// pluck(users, "nmae"); // not assignable to keyof User
console.log(names, ids);
Inference sites
A type parameter can only be inferred from a position where it appears in the parameter list. If
it appears only in the return type, there is nothing to infer from — and the result is a silent
unknown or whatever the caller asserts:
// Nothing to infer from. The caller must pass T, or get unknown.
function parse<T>(json: string): T {
return JSON.parse(json) as T;
}
const a = parse("{}"); // unknown — and `as T` was a lie either way
const b = parse<{ id: number }>("{}"); // the caller chose, and nothing checked it
console.log(a, b);
That signature is a common anti-pattern: it looks generic but is an assertion with extra steps.
The honest version returns unknown and makes the caller narrow, or takes a validator:
function parse(json: string): unknown {
return JSON.parse(json);
}
function parseWith<T>(json: string, check: (value: unknown) => T): T {
return check(JSON.parse(json));
}
const user = parseWith("{}", (value) => value as { id: number });
console.log(parse("{}"), user);
Now T has an inference site — the validator’s return type — so the caller writes nothing and the
type comes from something that actually runs.
T appears in |
Inferred from the call? |
|---|---|
| A parameter type | yes |
A parameter’s nested shape (T[], { value: T }) |
yes |
| A callback’s return type | yes |
| A callback’s parameter type | yes, contextually — the callback gets typed in turn |
| Only the return type | no — unknown, or whatever the caller writes |
A default (<T = X>) |
used only when inference found nothing |
Widening, and the three ways to stop it
function wrap<T>(value: T) { return { value }; }
const a = wrap("hello"); // { value: string } — widened
const b = wrap<"hello">("hello"); // explicit
const c = wrap("hello" as const); // as const at the call site
function keep<const T>(value: T) { return { value }; }
const d = keep("hello"); // { value: "hello" } — const type parameter
function narrow<T extends string>(value: T) { return { value }; }
const e = narrow("hello"); // { value: "hello" } — constrained to a primitive
console.log(a.value, b.value, c.value, d.value, e.value);
Five spellings of nearly the same call, three different inferred types. The rule: a literal
inferred into a plain T widens to its base type, and a constraint to a primitive or to a union
of literals keeps it narrow. const T (TypeScript 5.0) is the explicit way to say “do not widen
anything here”, and it is what makes a configuration helper preserve the shape it was handed.
function defineRoutes<const T extends Record<string, string>>(routes: T) { return routes; }
const routes = defineRoutes({ home: "/", users: "/users" });
type Route = typeof routes[keyof typeof routes]; // "/" | "/users", not string
const route: Route = "/users";
console.log(route);
Constraints that reference each other
A parameter can be constrained by another, which is where generics stop being a type-safe any
and start encoding relationships:
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
function setAll<T, K extends keyof T>(items: T[], key: K, value: T[K]): void {
for (const item of items) item[key] = value;
}
interface User { id: number; name: string }
const users: User[] = [{ id: 1, name: "Ana" }];
setAll(users, "name", "Beto");
// setAll(users, "name", 42); // 42 is not assignable to string
console.log(get(users[0]!, "name"));
value: T[K] is the part that pays: the third argument’s type depends on the second argument’s
value. No non-generic signature can express that.
Defaults
interface State<Data = unknown, Err = Error> {
data: Data | null;
error: Err | null;
}
const a: State = { data: null, error: null };
const b: State<string> = { data: "x", error: null };
const c: State<string, string> = { data: "x", error: "bad" };
console.log(a.data, b.data, c.error);
A default makes a parameter optional at the use site. It is not a constraint and does not restrict
anything — <T = string> still accepts a number. The two are often wanted together:
interface Paged<T extends object = Record<string, unknown>> {
items: T[];
total: number;
}
const page: Paged = { items: [{ anything: 1 }], total: 1 };
console.log(page.total);
Generic constraints versus overloads
Both make one function serve several shapes, and they fail differently:
// Overloads: a fixed menu, each entry independently typed.
function parse(value: string): string[];
function parse(value: number): number[];
function parse(value: string | number): unknown[] {
return [value];
}
// A generic: one rule, open to types nobody has written yet.
function wrap<T>(value: T): T[] { return [value]; }
const a = parse("x"); // string[]
const b = wrap(new Date()); // Date[]
console.log(a, b);
Reach for a generic when the relationship between input and output is uniform; reach for overloads when the shapes are genuinely unrelated, or when the return type depends on the number of arguments. Overloads have a real cost: the implementation signature is unchecked against them, so a mismatch is yours to notice.
Variance annotations
in and out are not features so much as assertions about a parameter’s position, used in large
codebases to make a type error point at the declaration rather than at a use site 40 files away:
interface Producer<out T> { get(): T } // T only in output position
interface Consumer<in T> { set(value: T): void } // T only in input position
interface Box<in out T> { get(): T; set(value: T): void }
declare const producer: Producer<string>;
const wider: Producer<unknown> = producer; // covariant — allowed
console.log(typeof producer.get, typeof wider.get);
They change nothing about what is allowed; the compiler computes variance from the structure
anyway. Writing out T and then using T in a parameter position is an error at the interface —
which is the point. Skip them unless compile performance or error locality is a real problem.
Designing a generic signature
The test of a generic API is whether callers ever write type arguments. Three rules, in order of value:
- Put every parameter in an inferable position. If a caller must write
fn<Thing>(...), the signature is asking them to do the compiler’s job. - Constrain to the smallest thing that works.
T extends { id: string }documents the requirement and gives a readable error; an unconstrainedTthat is indexed inside the body produces an error nobody can act on. - One parameter per independent degree of freedom. Two parameters that always vary together should be one, derived from the other with an indexed access.
// Hard to use: nothing to infer from, no constraint.
// function badFind<T, R>(items: unknown[], key: string): R
// Easy to use: both parameters inferred, both constrained.
function find<T extends object, K extends keyof T>(
items: readonly T[],
key: K,
value: T[K],
): T | undefined {
return items.find((item) => item[key] === value);
}
interface User { id: number; name: string }
const users: User[] = [{ id: 1, name: "Ana" }];
console.log(find(users, "name", "Ana"));
// find(users, "name", 42); // caught
Common mistakes
A type parameter that only appears in the return type
Mistake. function get<T>(url: string): Promise<T>.
Why it fails. There is no inference site, so T is whatever the caller claims and nothing
verifies it — an as with a nicer syntax.
What to do instead. Return unknown, or take a parser/validator argument so T is inferred
from something real.
Constraining in the hope of steering inference
Mistake. Expecting T extends Base to make T come out as Base.
Why it fails. Inference runs first and uses the arguments; the constraint only validates the
result afterwards.
What to do instead. If you want the parameter type, annotate the parameter. Use the constraint
for what it does: rejecting arguments and keeping literals narrow.
One type parameter per argument, out of habit
Mistake. function merge<A, B, C>(a: A, b: B, c: C) where all three are the same shape.
Why it fails. Three independent parameters allow combinations the function cannot handle, and
the error surfaces inside the body rather than at the call.
What to do instead. One parameter, or one constrained by another, so the relationship is in
the signature.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does a default type parameter — <T = string> — change?
A type parameter used in only one place is usually not doing any work.
What is wrong with this signature?
function log<T>(value: T): void {
console.log(value);
}What is a generic constructor signature — new () => T — used for?
A generic function body sees the constraint, not the eventual type argument.
Why is this assignment rejected inside the function?
function reset<T extends { count: number }>(item: T): T {
const next: T = { ...item, count: 0 };
return next;
}Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.