TypeScript Advanced Types: The Complete Guide
TypeScript advanced types in depth: conditional types, infer, mapped types, template literals, satisfies, variance, narrowing, and tested real-world patterns.
Introduction
TypeScript’s type system is a programming language of its own. Beyond interfaces and basic generics, you can compute new types from old ones, extract pieces of a type with pattern matching, and encode business rules so that illegal states fail at compile time instead of in production. Teams that master this layer ship APIs, state machines, and domain models where entire classes of bugs simply can’t be written down.
That power has a cost. Type-level code is harder to read, harder to debug, and easy to over-engineer. This guide covers the four pillars of type-level programming (conditional types, infer, mapped types, and template literal types) plus the parts most guides skip: satisfies and as const, type predicates, variance annotations, and the built-in utility type catalog. Every example was compiled with tsc --strict, and the companion repository contains a runnable playground with type-level tests.
You should already be comfortable with generics, union types, and keyof. If you want a cookbook of ready-made utility types first, see TypeScript Utility Types and Generics. This guide focuses on how the machinery works and when each tool is the right choice.
Conditional Types
A conditional type selects one of two types based on whether a type is assignable to another, following the shape T extends U ? X : Y. Think of extends here as “is a subtype of” — the check is resolved entirely at compile time. This is the foundation on which almost every other advanced feature is built: infer only works inside a conditional type, and distribution over unions is a property of conditional types.
// Conditional types: T extends U ? X : Y
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>; // false
type C = IsString<string | number>; // boolean (distributes: true | false)
// The standard library is built on this pattern
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type T1 = MyExclude<"a" | "b" | "c", "a">; // "b" | "c"
type T2 = MyExtract<string | number | boolean, number>; // number
Conditional types compose. Chaining extends clauses produces the type-level equivalent of an if/else chain, which is how you encode a lookup table in the type system:
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
T extends undefined ? "undefined" :
T extends Function ? "function" :
"object";
type N1 = TypeName<"hello">; // "string"
type N3 = TypeName<() => void>; // "function"
type N4 = TypeName<{ a: 1 }>; // "object"
A real use case: modeling an API response whose shape depends on the status code. The key detail is keeping the status and the payload as separate type parameters; conflating them produces types that look clever but describe nothing real.
// The status selects the shape; the payload is a second parameter
type ApiResponse<S extends number, T> =
S extends 200 ? { status: 200; data: T } :
S extends 400 ? { status: 400; error: string } :
S extends 500 ? { status: 500; error: string; retryAfter: number } :
never;
type OkUser = ApiResponse<200, { name: string }>;
// { status: 200; data: { name: string } }
type BadRequest = ApiResponse<400, { name: string }>;
// { status: 400; error: string }
Note that ApiResponse resolves to never for unlisted statuses, which makes an unsupported code a compile error — that’s the point of pushing rules into the type system. The TypeScript handbook page on conditional types covers additional corners like conditional type constraints.
The infer Keyword
Inside the extends clause of a conditional type, infer declares a type variable that TypeScript fills in by pattern matching. It is the type-level equivalent of destructuring: if the type matches the pattern, you capture the piece you marked with infer; if it doesn’t, the conditional falls through to the false branch.
// Extract the return type of a function — this is how ReturnType works
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type R1 = MyReturnType<() => string>; // string
type R2 = MyReturnType<(a: number) => boolean>; // boolean
// Unwrap a Promise recursively, handling nested promises
type MyAwaited<T> =
T extends Promise<infer U> ? MyAwaited<U> :
T;
type A1 = MyAwaited<Promise<string>>; // string
type A2 = MyAwaited<Promise<Promise<number>>>; // number
type A3 = MyAwaited<string | Promise<boolean>>; // string | boolean (distributes)
The most useful infers sit inside structural patterns: arrays, tuples, function signatures, object shapes. You can infer several positions in one pattern, and combine them with constraints:
// Array element type
type ElementOf<T> = T extends (infer E)[] ? E : never;
type E1 = ElementOf<string[]>; // string
// First argument of a function
type FirstParam<T> = T extends (arg: infer P, ...rest: any[]) => any ? P : never;
type P1 = FirstParam<(id: string, opts?: object) => void>; // string
// All values of an object
type ValueOf<T> = T extends Record<any, infer V> ? V : never;
type V1 = ValueOf<{ a: string; b: number }>; // string | number
// Deep-flatten nested arrays
type DeepFlatten<T> =
T extends (infer U)[] ? DeepFlatten<U> :
T;
type F1 = DeepFlatten<number[][][]>; // number
Two caveats worth knowing. First, (infer E)[] only matches mutable arrays; readonly T[] and tuples need their own pattern (T extends readonly (infer E)[]). Second, the real Awaited also unwraps PromiseLike and thenables, which this simplified version doesn’t; when in doubt, use the built-in.
Mapped Types
Mapped types generate an object type by iterating over the keys of another type: { [K in keyof T]: ... }. They answer the question “what would this shape look like if I changed every property the same way?”: the mechanism behind Partial, Readonly, Required, Pick, and Omit.
// The classics, reimplemented so you can see the mechanism
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] }; // -? removes optionality
type User = { id: string; name: string; email: string };
type DraftUser = MyPartial<User>;
// { id?: string; name?: string; email?: string }
The -? and -readonly modifiers remove modifiers; +? and +readonly add them (the + is implied, so you rarely write it). Mapped types over unions and tuples also work — { [K in keyof [string, number]]: ... } iterates tuple indices, which powers several advanced patterns.
Key remapping with as
The as clause in a mapped type lets you rename or filter keys while iterating. Filtering works by mapping a key to never, which drops it from the output entirely.
// camelCase to snake_case, done recursively one character at a time
type SnakeCase<S extends string, First extends boolean = true> =
S extends `${infer C}${infer Rest}`
? C extends Lowercase<C>
? `${Lowercase<C>}${SnakeCase<Rest, false>}`
: `${First extends true ? "" : "_"}${Lowercase<C>}${SnakeCase<Rest, false>}`
: "";
type ToSnakeCase<T> = {
[K in keyof T as SnakeCase<string & K>]: T[K];
};
type SnakeUser = ToSnakeCase<{ userId: number; firstName: string }>;
// { user_id: number; first_name: string }
// Filter keys by value type
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
type FunctionsOnly = PickByValue<
{ id: number; onClick: () => void; onChange: (v: string) => void },
Function
>;
// { onClick: () => void; onChange: (v: string) => void }
The non-recursive version of SnakeCase you may have seen online splits the string at the first character and produces u_serid. Recursion is what makes it correct. When you build a key-remapping type, always test it against two or three concrete inputs; the type system won’t warn you when the output is wrong, only when the syntax is invalid.
PickByValue is worth pausing on because it shows the composition pattern: key remapping (as), a conditional type (extends V), and never as a filter. Most real-world mapped types are exactly this: two or three primitives composed together. For more ready-to-use recipes in this style, check TypeScript Utility Types and Generics.
Template Literal Types
Template literal types build string types with the same backtick syntax as template literal strings: `prefix-${T}`. When any interpolated position is a union, the result is the cartesian product of the unions — one string per combination — which turns string manipulation into a generative tool.
// String concatenation at the type level
type EventName = `on${"Click" | "Change" | "Submit"}`;
// "onClick" | "onChange" | "onSubmit"
// Paired with the intrinsic string types
type Getter<K extends string> = `get${Capitalize<K>}`;
type G1 = Getter<"name">; // "getName"
// Route parameter extraction — infer inside string patterns
type ExtractParams<S extends string> =
S extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param]: string } & ExtractParams<`/${Rest}`>
: S extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
type Params = ExtractParams<"/users/:userId/posts/:postId">;
// { userId: string } & { postId: string }
TypeScript ships four intrinsic string types (Uppercase, Lowercase, Capitalize, Uncapitalize) which are implemented in the compiler rather than in type-space, so they’re cheap to evaluate. You’ll use them constantly alongside template literals (the SnakeCase type above relies on Lowercase and Uncapitalize).
Where template literals really shine is constraining strings without enumerating every value:
// Event names that must start with "on" followed by a capital letter
type HandlerName = `on${Capitalize<string>}`;
const good: HandlerName = "onSubmit"; // OK
// const bad: HandlerName = "onsubmit"; // Error — not capitalized
// CSS-like unit strings
type CssLength = `${number}px` | `${number}rem` | `${number}%`;
const width: CssLength = "2.5rem"; // OK
// const bad: CssLength = "2.5"; // Error — missing unit
Distributive Conditional Types
When the checked type of a conditional type is a “naked” type parameter (just T, not T[] or [T]), the conditional distributes over each member of a union, evaluates separately, and unions the results. IsString<string | number> becomes IsString<string> | IsString<number> = true | false = boolean.
type ToArray<T> = T extends any ? T[] : never;
type Arr = ToArray<string | number>;
// string[] | number[] — NOT (string | number)[]
// Wrap the parameter to prevent distribution
type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;
type Arr2 = ToArrayNonDist<string | number>;
// (string | number)[]
// Distribution is what makes union filtering possible
type OnlyStrings<T> = T extends string ? T : never;
type S1 = OnlyStrings<"a" | 1 | "b" | 2>; // "a" | "b"
Distribution is usually what you want: Exclude, Extract, and NonNullable all rely on it. Wrap T in a tuple [T] extends [any] when you need the union treated as a single value. A subtle edge case: T extends any ? X : Y evaluated with T = never produces never, not X, because never is the empty union and there’s nothing to distribute over. That quirk bites people building “does T extend never” checks — use [T] extends [never] instead.
satisfies and as const
as const and satisfies solve the same underlying problem (TypeScript widening literal types) from opposite directions. as const freezes a value at its narrowest possible type; satisfies checks a value against a type without widening it, keeping the literal precision for later inference.
// Without as const, object properties widen
const config1 = { mode: "dev", retries: 3 };
// { mode: string; retries: number }
const config2 = { mode: "dev", retries: 3 } as const;
// { readonly mode: "dev"; readonly retries: number } — and arrays become readonly tuples
// satisfies checks the shape but preserves the literal type
const routes = {
home: "/",
user: "/users/:id",
} satisfies Record<string, `/${string}`>;
type Route = (typeof routes)[keyof typeof routes]; // "/" | "/users/:id"
// With `: Record<...>` instead, Route would be just `string`
Since TypeScript 5.0, you can get the same precision in generics with the const type parameter modifier, which is often the better tool inside library code:
// Without const: names widens to string[]
function makeTable<T extends { columns: string[] }>(t: T) { return t; }
// With const: names keeps its literal tuple type
function makeTable2<const T extends { columns: readonly string[] }>(t: T) { return t; }
const table = makeTable2({ columns: ["id", "name"] });
// columns: readonly ["id", "name"] — Column type can extract "id" | "name"
Rule of thumb: as const on the value, satisfies when you need both validation and literal inference, const T in generic signatures. The satisfies release notes (TS 4.9) show the canonical motivation — property lookup errors without losing key inference.
Type Predicates and Assertion Functions
Narrowing at runtime often needs a corresponding narrowing at the type level. A type predicate x is T tells the compiler that when your function returns true, the argument is actually of type T. An assertion function asserts x is T throws otherwise. Together they let you move runtime checks into the type system instead of scattering casts.
function isString(x: unknown): x is string {
return typeof x === "string";
}
const values: unknown[] = ["a", 1, "b"];
const strings = values.filter(isString); // string[], not unknown[]
// Assertion function: throws or narrows
function assertDefined<T>(x: T | null | undefined): asserts x is T {
if (x === null || x === undefined) throw new Error("Value is missing");
}
declare const maybeUser: { name: string } | undefined;
assertDefined(maybeUser);
maybeUser.name; // OK — narrowed after the call
Custom guards compose beautifully with the discriminated union pattern. If you rely on switch statements for state handling, Exhaustive Type Checking with Discriminated Unions is the natural companion to this section. One honest limitation: a wrong predicate signature (x is string on a function that actually checks numbers) compiles silently and poisons every narrowing downstream. Treat predicates like casts — verify the implementation manually.
Variance Annotations
Since TypeScript 4.7 you can annotate how a generic parameter is used with in (contravariant) and out (covariant). The compiler uses these annotations to check assignability between instantiations of your generic, and, just as valuable, it fails loudly when you accidentally use a parameter in the wrong position.
interface Producer<out T> {
next(): T;
}
interface Consumer<in T> {
accept(value: T): void;
}
// Covariance: Producer<"a"|"b"> is assignable to Producer<string>
// Contravariance: Consumer<string> is assignable to Consumer<"a"|"b">
// TypeScript rejects wrong positions at declaration time:
// interface Bad<out T> { set(v: T): void }
// Error: 'T' appears in a contravariant position
Most application code never needs these annotations; the compiler infers variance correctly. They matter when you publish generic interfaces or build typed containers (observables, emitters, repositories) where variance bugs surface as confusing assignability errors in consumer code. Declaring the intent explicitly turns a cryptic downstream error into a clear error at your declaration.
The Built-in Utility Type Catalog
Before writing a custom mapped or conditional type, check whether the standard library already ships it. The built-ins are battle-tested, handle edge cases you’ll forget (like PromiseLike in Awaited), and signal intent to readers instantly.
| Utility | Purpose | Example result |
|---|---|---|
Partial<T> / Required<T> | All properties optional / required | { a?: string } |
Readonly<T> / Mutable<T> (custom) | Freeze / unfreeze properties | { readonly a: string } |
Pick<T, K> / Omit<T, K> | Keep / drop listed keys | Pick<User, "id"> |
Record<K, V> | Object type with key/value types | Record<string, number> |
Exclude<T, U> / Extract<T, U> | Remove / keep union members | "b" | "c" |
NonNullable<T> | Remove null and undefined | string |
ReturnType<F> / Parameters<F> | Function output / input tuple | string, [id: string] |
Awaited<T> | Unwrap nested promises | Awaited<Promise<number>> → number |
InstanceType<C> / ConstructorParameters<C> | Class instance / ctor args | User, [name: string] |
NoInfer<T> (TS 5.4) | Block inference from a position | prevents unwanted widening |
Uppercase Lowercase Capitalize Uncapitalize | Intrinsic string transforms | "GET" → "get" |
Reimplementing a built-in (as the earlier sections do) is a great way to learn the mechanism, and a poor habit in production code. Custom types like MyPartial shadow the global name, confuse tooling, and silently diverge from the real semantics. Reach for the built-in first; extend only when it doesn’t express what you need.
Advanced Patterns
These four patterns combine everything above into constructs you’d actually ship. Each is the fixed, compiled version of a pattern that circulates online in subtly broken form. The companion repository lets you run them and the type tests that verify them.
Type-safe event emitter
Template literal types plus keyof produce an emitter where event names and payloads are checked together:
type Events = {
"user:created": { id: string };
"user:deleted": { id: string };
"order:paid": { orderId: string; amount: number };
};
class TypedEmitter<T extends Record<string, unknown>> {
private handlers = new Map<keyof T, Set<(data: never) => void>>();
on<K extends keyof T>(event: K, handler: (data: T[K]) => void): void {
const set = this.handlers.get(event) ?? new Set();
set.add(handler as (data: never) => void);
this.handlers.set(event, set);
}
emit<K extends keyof T>(event: K, data: T[K]): void {
this.handlers.get(event)?.forEach((h) => (h as (d: T[K]) => void)(data));
}
}
const emitter = new TypedEmitter<Events>();
emitter.on("user:created", (data) => console.log(data.id)); // data: { id: string }
emitter.emit("order:paid", { orderId: "o-1", amount: 9.99 }); // OK
// emitter.emit("order:paid", { orderId: "o-1" }); // Error: missing amount
Type-safe API client
The tricky part of a typed route table is that not every route has every option: POST has body but no query. Indexing the union directly (ApiRoutes[K]["query"]) fails to compile because some members lack the key. The fix is a conditional lookup that yields never for missing keys, then making options required or forbidden per route:
type ApiRoutes = {
"GET /users": { query: { page?: number }; response: User[] };
"GET /users/:id": { params: { id: string }; response: User };
"POST /users": { body: { name: string; email: string }; response: User };
"DELETE /users/:id": { params: { id: string }; response: void };
};
type ApiKey = keyof ApiRoutes;
// Look up each optional slot; absent keys yield never
type Params<K extends ApiKey> = ApiRoutes[K] extends { params: infer P } ? P : never;
type Query<K extends ApiKey> = ApiRoutes[K] extends { query: infer Q } ? Q : never;
type BodyOf<K extends ApiKey> = ApiRoutes[K] extends { body: infer B } ? B : never;
type ResponseOf<K extends ApiKey> = ApiRoutes[K]["response"];
// Required when present, forbidden when absent — [X] avoids distribution
type Options<K extends ApiKey> =
([Params<K>] extends [never] ? { params?: never } : { params: Params<K> }) &
([Query<K>] extends [never] ? { query?: never } : { query: Query<K> }) &
([BodyOf<K>] extends [never] ? { body?: never } : { body: BodyOf<K> });
type HasOptions<K extends ApiKey> =
[Params<K> | Query<K> | BodyOf<K>] extends [never] ? false : true;
async function api<K extends ApiKey>(
key: K,
...args: HasOptions<K> extends true ? [options: Options<K>] : []
): Promise<ResponseOf<K>> {
const options = (args[0] ?? {}) as Options<K>;
const [method, rawPath] = key.split(" ") as [string, string];
let path = rawPath;
const params = (options as { params?: Record<string, string> }).params;
if (params) {
for (const [name, value] of Object.entries(params)) {
path = path.replace(`:${name}`, String(value));
}
}
const res = await fetch(path, { method });
return res.json() as Promise<ResponseOf<K>>;
}
const users = await api("GET /users", { query: { page: 1 } }); // User[]
const user = await api("GET /users/:id", { params: { id: "u-1" } }); // User
// await api("GET /users/:id"); // Error: params required
// await api("POST /users", { body: { name: "A" } }); // Error: email missing
It’s the pattern behind real typed clients: declare the contract once, let conditional lookups and never enforcement do the checking. The [X] extends [never] trick (wrapping in tuples to test without distributing) is the same one from the distributive section.
Type-safe state machine
Event names live inside each state’s transitions record, so extracting them means collecting the keys of every transitions object: { [K in keyof T]: keyof T[K]["transitions"] }[keyof T]: a mapped type whose result is indexed by the union of its own keys, collapsing to the union of event names.
type StateMachine<T extends Record<string, { transitions: Record<string, string> }>> = {
[K in keyof T]: { state: K; transitions: keyof T[K]["transitions"] };
};
type TrafficLight = {
red: { transitions: { go: "green" } };
green: { transitions: { warn: "yellow" } };
yellow: { transitions: { stop: "red" } };
};
type TrafficState = StateMachine<TrafficLight>[keyof StateMachine<TrafficLight>];
// { state: "red"; transitions: "go" }
// | { state: "green"; transitions: "warn" }
// | { state: "yellow"; transitions: "stop" }
type EventsOf<T extends Record<string, { transitions: Record<string, string> }>> =
{ [K in keyof T]: keyof T[K]["transitions"] }[keyof T];
class Machine<T extends Record<string, { transitions: Record<string, string> }>> {
constructor(private current: keyof T, private config: T) {}
transition(event: EventsOf<T>): void {
const stateConfig = this.config[this.current];
const next = stateConfig.transitions[event as string];
if (!next) throw new Error(`Invalid transition: ${String(event)} from ${String(this.current)}`);
this.current = next as keyof T;
}
get state(): keyof T {
return this.current;
}
}
const traffic = new Machine<TrafficLight>("red", {
red: { transitions: { go: "green" } },
green: { transitions: { warn: "yellow" } },
yellow: { transitions: { stop: "red" } },
});
traffic.transition("go"); // red → green
traffic.transition("warn"); // green → yellow
traffic.transition("stop"); // yellow → red
Note the honest boundary: EventsOf validates that the event exists somewhere in the machine, not that it’s legal from the current state; that check still happens at runtime in transition. Tracking the current state in the type parameter is possible but costs real complexity; for most apps this split is the right trade-off.
Branded types and smart constructors
Branding attaches a phantom tag to a primitive so two strings that mean different things (a user ID and an order ID) are no longer interchangeable. Pair it with a smart constructor so the only way to obtain the branded value is through validation.
declare const brand: unique symbol;
type Brand<T, B> = T & { [brand]: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Email = Brand<string, "Email">;
// The only constructor: validates the real UUID format, not just the length
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function createUserId(raw: string): UserId {
if (!UUID_RE.test(raw)) throw new Error(`Invalid UUID: ${raw}`);
return raw as UserId;
}
function createEmail(raw: string): Email {
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(raw)) throw new Error(`Invalid email: ${raw}`);
return raw as Email;
}
function getUser(id: UserId): UserId {
return id;
}
const userId = createUserId("3f2b9c1a-7e8d-4a5b-9c6d-1e2f3a4b5c6d");
declare const orderId: OrderId;
getUser(userId); // OK
// getUser(orderId); // Error: OrderId is not assignable to UserId
The regex detail matters: a length-plus-charset check like /^[a-f0-9-]{36}$/ accepts 36 dashes and rejects uppercase UUIDs. Branding is compile-time only: as anywhere in the codebase can still forge a brand, so keep the cast confined to the constructor and lint for stray assertions if the invariant is critical.
Overloads vs Conditional Types
When a function’s return type depends on its arguments, you’ve got two tools: overload signatures and a single signature returning a conditional type. Overloads are simpler and produce clearer errors; conditional types are composable and scale to many cases without combinatorial signatures.
// Overloads: explicit, friendly errors — but one signature per case
function parse(input: string): { raw: string };
function parse(input: number): { parsed: number };
function parse(input: string | number) {
return typeof input === "string" ? { raw: input } : { parsed: input };
}
// Conditional: one signature, scales — but errors point at the type, not the call
type ParseResult<T> = T extends string ? { raw: string } : T extends number ? { parsed: number } : never;
function parse2<T extends string | number>(input: T): ParseResult<T> {
return (typeof input === "string" ? { raw: input } : { parsed: input }) as ParseResult<T>;
}
Choose overloads when the cases are few and disjoint (two or three input shapes). Choose conditional types when the mapping is systematic (one rule applied across a union) or when the result must be computed inside other types, where overloads can’t go. The failure mode to avoid is a single conditional type trying to do the job of five overloads: at that point the type is harder to read than the function it describes.
Performance and Debugging
Type-level code runs in the checker, and it’s got real limits. Deep recursion hits the instantiation depth cap (error: “Type instantiation is excessively deep and possibly infinite”), and highly distributed conditionals over big unions can make IntelliSense crawl. Most performance problems have the same root cause: asking the checker to evaluate more than necessary.
// Defer evaluation with an interface "box" instead of a raw recursive alias
interface Box<T> { value: T }
// Split a huge conditional into named intermediate steps
type Step1<T> = T extends { data: infer D } ? D : never;
type Step2<T> = T extends { meta: infer M } ? M : never;
type ApiShape<T> = { data: Step1<T>; meta: Step2<T> };
// Easier to hover, easier to locate, and the checker caches each step
Debugging techniques that actually help: isolate a type in a scratch file and hover it; use type Expect<T extends true> and type Equal<A, B> assertions (from expect-type or tsd) to pin behavior in tests; and simplify by feeding the type concrete inputs until the wrong branch reveals itself. If a conditional is “impossible” to satisfy, suspect distribution or an unintended never first: they’re the two most common culprits.
When to Use and When Not To
Use type-level programming when the compiler can enforce a rule callers would otherwise break: required-vs-forbidden options per route, event-payload matching, branded identifiers, exhaustive unions. These are cases where a wrong call is a real bug, and the type is documentation that can’t drift out of date.
Don’t use it to be clever. A deeply nested conditional that saves ten lines of duplication but costs every reader ten minutes is a bad trade. Ask three questions before reaching for infer: can a plain union or discriminated union express this? will the error message make sense to the person who hits it? and does the team that owns this file write types at this level? If any answer is no, choose the boring option — overloads, unions, or an explicit interface.
What Works
- Start from a concrete case. Write the input and the expected output type as comments, then build the type that produces it. Trying to write the general type first is how you end up with
u_serid. - Test types like code.
expect-typeortsdassertions (expectTypeOf<SnakeCase<"userId">>().toEqualTypeOf<"user_id">()) catch silent wrongness that compiles fine. Keep the tests next to the types. - Prefer the built-in utility types, and compose them before inventing primitives.
Exclude<keyof T, "id">beats a customOmitKeysmost days. - Keep every branded-type cast inside its smart constructor. The brand is only as strong as the number of
asstatements that can forge it. - Name intermediate steps in long conditionals (
Step1,Step2). It gives the checker cacheable units and gives readers checkpoints, doubly valuable when the type is wrong.
Common Mistakes
- Indexing a union by a key that only some members have.
ApiRoutes[K]["query"]fails to compile when a route lacksquery; useApiRoutes[K] extends { query: infer Q } ? Q : neverinstead. This is the single most common broken pattern in typed clients. - Forgetting that conditional types distribute.
ToArray<string | number>isstring[] | number[], not(string | number)[]; wrap the check in[T]when you want the union whole. The reverse also bites: testingT extends neverinstead of[T] extends [never]silently evaluates tonever. - Recursion without a base case or a termination guarantee.
type Snake<S> = ...Snake<S>...that never shrinks its input hits “type instantiation is excessively deep.” Every recursive type should consume its input (a char, an element, a key) on each step. - Letting the compiler infer where you wanted literals.
{ home: "/" }as aRecordwidens values tostringand loses the route table you built. That’s whatsatisfiesandas constexist for. - Trusting a wrong type predicate.
x is stringon a function that checkstypeof x === "number"compiles and corrupts every downstream narrowing. Predicates are unchecked assertions — verify them by hand.
Further Reading
- TypeScript Handbook: Conditional Types — distribution,
infer, and constraints in depth - TypeScript Handbook: Mapped Types — key remapping and modifiers
- TypeScript Handbook: Template Literal Types — string manipulation at the type level
- TypeScript 4.9 release notes:
satisfies— the operator’s canonical use cases - type-fest — a large collection of production-grade utility types worth reading for technique
- Exhaustive Type Checking with Discriminated Unions — the narrowing counterpart to this guide
- TypeScript Utility Types and Generics — cookbook-style utilities built on these primitives
Frequently Asked Questions
How do I extract the return type of a function?
Use infer inside a conditional: type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never. The pattern matches the signature and captures whatever sits in the infer position. The standard library already ships this as ReturnType<T> — reimplement it to learn the mechanism, use the built-in in real code.
Why doesn't my conditional type do anything with a union?
It does: it distributes. T extends U ? X : Y with T = A | B evaluates once per member and unions the results, which is usually the behavior you want. If you need the union checked as a single value, wrap the parameter in a tuple: [T] extends [U] ? X : Y.
What's the difference between satisfies and as const?
as const narrows a value to its literal type and makes everything readonly; it doesn't check anything. satisfies validates a value against a type while keeping the literal inference, so { home: "/" } satisfies Record<string, string> both checks the shape and preserves "/" as the value type. Reach for as const to freeze, satisfies to validate-plus-keep.
When should I use infer instead of indexed access?
Indexed access (T["key"]) works when you already know the key. Use infer when the piece you want is positional or structural: the return of any function, the element of any array, the param segment of any route string. If you can write the key literally, you don't need pattern matching.
Can type-level code be too complex to be worth it?
Yes, and it's the most common failure mode of advanced types. A conditional with four levels of nesting that saves a little duplication usually costs more in review time and error-message quality than it returns. If a union, an overload, or an explicit interface expresses the same rule, that's the better type.
How do I test that my types actually work?
With compile-time assertions: expectTypeOf<T>().toEqualTypeOf<U>() from expect-type, or the tsd library. They fail the build when the computed type differs from what you declared. Since the type system won't flag a type that's valid syntax but wrong semantics (like a SnakeCase that emits u_serid), tests are the only safety net.
Related Resources
Complete Guide to React Server Components: RSC Architecture
A deep dive into React Server Components: the RSC payload, server-client boundaries, data loading, streaming, Next.js caching, and server actions.
RecipeBuild Reusable Utility Types with Generics
How to create reusable TypeScript utility types using conditional types, mapped types, template literals, and generic constraints for type-safe APIs.
RecipeExhaustive Type Checking with Discriminated Unions
How to use TypeScript discriminated unions for exhaustive type checking, ensuring all cases are handled at compile time with never type assertions.
GuideReact State Management: Zustand, Jotai, TanStack Query
How to choose and combine React state management tools: Context API, Zustand, Jotai, and TanStack Query for server state, with patterns and a decision framework.