Lesson 43 of 50TypeScript
Generics and Type-Level Patterns in Depth
How TypeScript infers type arguments, why variance makes arrays unsound, and the patterns behind typed emitters, deep paths and type tests.
Sooner or later you write a helper the whole team uses: a typed pick, an event bus, a config loader. The first version compiles, but callers get string where they wanted "admin", or a typo in an event name slips through, or the editor freezes on a type nobody can read. Writing generics that feel good to call is a different skill from using them. This lesson is about that skill: how inference chooses a type, where the type system is deliberately unsound, the handful of type-level patterns that show up in real libraries, and how to test types so they stay correct. It assumes Generics and Advanced Types, so mapped, conditional and template literal types are not re-explained.
How TypeScript picks a type argument
When you call first(["admin", "member"]) without writing <...>, the checker infers T. It walks the arguments, and every place where T appears in a parameter type is an inference site. Each site produces a candidate. Then it combines the candidates and widens literal types if nothing asks it not to.
function first<T>(xs: T[]): T | undefined {
return xs[0];
}
const role = first(["admin", "member"]); // string | undefinedThe array literal ["admin", "member"] is inferred as string[], because a mutable array of literals widens. That is usually what you want for data, and rarely what you want for configuration.
const type parameters
TypeScript 5.0 added const before a type parameter. It tells inference to treat the argument as if it were written as const:
function firstConst<const T>(xs: readonly T[]): T | undefined {
return xs[0];
}
const role = firstConst(["admin", "member"]); // "admin" | "member" | undefinedThe readonly T[] is not required for the literals, but it lets callers also pass an array they already marked as const, which a mutable T[] would reject. Note what const does not do: it only affects literals written directly in the call. Pass a variable declared earlier with let or a plain array, and its type was already widened before the call. Library authors use const type parameters for route tables, permission lists and anything else where callers expect literal types without writing as const themselves.
NoInfer: blocking an inference site
Sometimes a parameter should use a type but not help decide it.
function createMachine<S extends string>(states: S[], initial: S) {
return { states, initial };
}
createMachine(["idle", "loading"], "done"); // no error! S became "idle" | "loading" | "done"Both parameters are inference sites, so "done" was added to the union. NoInfer<T> (TypeScript 5.4) removes a site from inference:
function createMachine<S extends string>(states: S[], initial: NoInfer<S>) {
return { states, initial };
}
createMachine(["idle", "loading"], "done");
// Error: Argument of type '"done"' is not assignable to parameter of type '"idle" | "loading"'.Now S is decided by states alone and initial is only checked against it. Use it for defaults, initial values and fallbacks.
S get in createMachine(["idle", "loading"], "done") without NoInfer?Variance: where the type system is unsound on purpose
Variance describes how a generic type's assignability follows its type argument. If Dog is assignable to Animal:
- Covariant:
Box<Dog>is assignable toBox<Animal>. Safe whenBoxonly produces values (return types, readonly properties). - Contravariant:
Handler<Animal>is assignable toHandler<Dog>. Safe when the type only consumes values (parameters). A function that handles any animal can handle a dog. - Invariant: neither direction. Correct for anything that both reads and writes.
A mutable array both reads and writes, so it should be invariant. TypeScript makes arrays covariant anyway, because the alternative breaks too much everyday code. The price is a hole you can drive a cat through:
Press Run (⌘ Enter) to see what happens.The practical fix is to accept readonly Animal[] in functions that only read. A readonly array cannot be pushed to, so the covariance becomes sound, and callers can still pass a Dog[].
Methods are checked more loosely than function properties
With strictFunctionTypes (part of strict), function parameters are checked contravariantly. But only for function-typed properties. Parameters of methods stay bivariant for compatibility with older DOM and library types.
type Animal = { name: string };
type Dog = Animal & { bark(): string };
interface WithMethod { handle(a: Animal): void }
interface WithProperty { handle: (a: Animal) => void }
const dogOnly = (d: Dog) => { d.bark(); };
const m: WithMethod = { handle: dogOnly }; // allowed: method bivariance
const p: WithProperty = { handle: dogOnly }; // Error: 'Animal' is not assignable to 'Dog'Both interfaces describe the same runtime object, yet only the property form catches that dogOnly will crash when given a plain animal. This is why some teams enable the typescript-eslint rule method-signature-style to require the property form in their own types.
strict on, which assignment compiles even though it can crash at runtime?in and out annotations
TypeScript works out variance by comparing structures, which can be slow for big generic types. You can state it with out (covariant), in (contravariant) or in out (invariant):
interface Producer<out T> { get(): T }
interface Consumer<in T> { take(value: T): void }The checker verifies the annotation is correct, then uses it as a shortcut. You will mostly meet these in library code and performance fixes, not in app code.
Distribution, the edge cases
Advanced Types showed that a conditional type over a bare type parameter distributes over a union. Two consequences catch people in interviews.
First, never is the empty union, so distributing over it produces nothing:
type IsNever<T> = T extends never ? true : false;
type A = IsNever<never>; // never, not true
type IsNeverFixed<T> = [T] extends [never] ? true : false;
type B = IsNeverFixed<never>; // trueWrapping both sides in a one-element tuple stops distribution, because [T] is no longer a bare type parameter.
Second, distribution can be used. UnionToIntersection turns A | B into A & B, and it is built from two facts: distribution makes one function type per member, and inferring from a parameter position (a contravariant site) combines candidates with & instead of |.
type UnionToIntersection<U> =
(U extends unknown ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
type R = UnionToIntersection<{ a: 1 } | { b: 2 }>; // { a: 1 } & { b: 2 }U is bare, so the first conditional runs once per union member.
Recursive types
Types can refer to themselves. The most useful one in practice describes any valid JSON:
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
const ok: Json = { tags: ["a", "b"], meta: { count: 2, next: null } };
const bad: Json = { at: new Date() }; // Error: Date is not assignable to JsonUse it as the parameter type of anything that calls JSON.stringify, and a Date, a Map or a function in the payload becomes a compile error instead of a silently lost field.
Recursive conditional types can also compute paths, which form libraries and i18n libraries use to type keys like "address.city":
type Paths<T> = T extends object
? {
[K in keyof T & string]: T[K] extends object ? K | `${K}.${Paths<T[K]>}` : K;
}[keyof T & string]
: never;
type Get<T, P extends string> = P extends `${infer Head}.${infer Rest}`
? Head extends keyof T
? Get<T[Head], Rest>
: never
: P extends keyof T
? T[P]
: never;
type User = { name: string; address: { city: string; geo: { lat: number } } };
type UserPath = Paths<User>;
// "name" | "address" | "address.city" | "address.geo" | "address.geo.lat"
type Lat = Get<User, "address.geo.lat">; // numberThe mapped type visits every string key of User.
These types are powerful and expensive. Every level multiplies the work, and a Paths over a large generated API schema can slow the editor for the whole team. The checker also stops deep recursion with "Type instantiation is excessively deep and possibly infinite". Add a depth limit for big inputs, and measure with the tools from The TypeScript Toolchain in 2026 before shipping one in a shared package.
Patterns you will meet in real code
A typed event emitter and a typed pick
Both follow one recipe: a generic constrained to keyof something, then an indexed access to get the matching value type.
Press Run (⌘ Enter) to see what happens.Inside on, p is typed { sku: string; qty: number } with no annotation, and bus.emit("cart:ad", ...) is a compile error. The single cast in pick ({} as Pick<T, K>) is the honest kind: a small helper whose loop makes the claim true.
A builder that remembers what you did
A builder can carry state in a type parameter, adding to it on every call:
type User = { id: string; name: string; email: string };
class Query<Row, Selected extends keyof Row = never> {
private readonly cols: (keyof Row)[];
constructor(cols: (keyof Row)[] = []) {
this.cols = cols;
}
select<K extends keyof Row>(...keys: K[]): Query<Row, Selected | K> {
return new Query<Row, Selected | K>([...this.cols, ...keys]);
}
run(rows: Row[]): Pick<Row, Selected>[] {
return rows.map((r) => {
const out = {} as Pick<Row, Selected>;
for (const c of this.cols) (out as Record<keyof Row, unknown>)[c] = r[c];
return out;
});
}
}
declare const users: User[];
const rows = new Query<User>().select("id").select("email").run(users);
rows[0]?.email; // OK
rows[0]?.name; // Error: Property 'name' does not existThis is the shape of Drizzle, Kysely and Zod's chained methods: each call returns a new type built from the old one.
Overloads, conditional return types, or neither
When the return type depends on the input, you have three tools.
// 1. Overloads: a list of signatures, then one implementation
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
// 2. A conditional return type
function parse2<T extends string | string[]>(input: T): T extends string ? number : number[] {
// The checker cannot narrow T here, so this needs a cast to compile
return (Array.isArray(input) ? input.map(Number) : Number(input)) as T extends string ? number : number[];
}Overloads read well in editor tooltips and work for two or three cases. Conditional return types scale to many cases, but the implementation almost always needs a cast, because narrowing input does not narrow T. The best option is often neither: two functions, parseOne and parseMany, with plain signatures. A seasoned reviewer asks "can this be two functions?" before approving clever types.
Making clever types readable
Type-level code has a user experience, and the users are your teammates hovering over a variable. Two habits make a large difference.
First, flatten intersections for display. Pick<User, "id"> & { role: Role } shows up in a tooltip exactly like that, which tells the reader nothing. A tiny identity mapped type forces the checker to print the resolved object:
type Prettify<T> = { [K in keyof T]: T[K] } & {};
type Raw = Pick<{ id: string; name: string }, "id"> & { role: "admin" };
type Shown = Prettify<Raw>; // hover shows { id: string; role: "admin" }The trailing & {} is a common trick to stop the editor from collapsing it back into the alias name. Libraries call this Simplify or Prettify, and it costs almost nothing.
Second, design for the error message, not only the happy path. When a call fails against a deep conditional type, the error often ends with not assignable to type 'never', which hides the real reason. Constrain type parameters as early as possible (K extends keyof T on the function, not a conditional inside the return type), because a constraint failure names the bad argument directly. If a helper needs more than a screen of type code, write down in a comment what it should accept and reject, and add type tests for both. Then ask whether a plainer API would do the job.
Testing types
A type helper is code, and it breaks like code. Vitest ships expectTypeOf for assertions that run in the type checker:
import { expectTypeOf, test } from "vitest";
import { pick } from "./pick";
test("pick keeps only the chosen keys", () => {
const user = { id: "u1", name: "Ada", passwordHash: "x" };
expectTypeOf(pick(user, "id", "name")).toEqualTypeOf<{ id: string; name: string }>();
expectTypeOf(pick(user, "id")).not.toHaveProperty("passwordHash");
// @ts-expect-error: "email" is not a key of user
pick(user, "email");
});Run them with vitest --typecheck, or rely on tsc in CI to check the file. @ts-expect-error is the other half: it fails if the next line has no error, so it proves that bad calls are still rejected. Prefer it to @ts-ignore, which hides errors forever, even after the code is fixed.
What does this print?
type Animal = { name: string };
type Dog = Animal & { bark(): string };
const dogs: Dog[] = [{ name: "Rex", bark: () => "Woof" }];
const animals: Animal[] = dogs;
animals.push({ name: "Tom" });
for (const d of dogs) {
try {
console.log(d.name, d.bark());
} catch (e) {
console.log(d.name, "crashed:", (e as Error).constructor.name);
}
}Match each problem to the tool that solves it.
Interview classics: DeepReadonly and Awaited
DeepReadonly is a recursive mapped type. The function check comes first, because functions are objects and you do not want to map over their properties:
type DeepReadonly<T> = T extends (...args: never[]) => unknown
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;Awaited unwraps promises recursively, and it matches any thenable (an object with a then method), not just Promise, because await works on thenables:
type MyAwaited<T> = T extends null | undefined
? T
: T extends object & { then(onfulfilled: infer F, ...args: infer _): unknown }
? F extends (value: infer V, ...args: infer _) => unknown
? MyAwaited<V>
: never
: T;
type N = MyAwaited<Promise<Promise<number>>>; // numberSay out loud why each branch exists: null and undefined pass through, a thenable is unwrapped by inferring the type its callback receives, and recursion handles nested promises.
- inference site
- A place in a parameter type where a type parameter appears. Each one contributes a candidate when TypeScript infers the type argument.
- const type parameter
<const T>: infers arguments as if they were writtenas const, keeping literal types.- NoInfer
- A utility type that removes a parameter from inference, so it is only checked against the type found elsewhere.
- variance
- How assignability of
Box<T>follows assignability ofT: covariant, contravariant, invariant or bivariant. - method bivariance
- Method parameters are checked in both directions even under
strictFunctionTypes, unlike function-typed properties. - recursive type
- A type that refers to itself, such as a JSON value or a dotted path union.
- type test
- An assertion checked by the compiler, such as
expectTypeOf(...).toEqualTypeOf<T>()or@ts-expect-error.