Lesson 42 of 50TypeScript
Advanced Types
Compute types from other types with keyof, typeof, indexed access, mapped, conditional and template literal types.
The utility types from the last lesson are not magic. Partial, Pick and ReturnType are a few lines of ordinary TypeScript, written with the tools in this lesson. Once you can read them, library types (React, Prisma, tRPC, Zod) stop looking like noise, and you can write your own when a codebase needs one. Senior interviews often include "implement Partial yourself" or "what does infer do?".
keyof and typeof in type position
You met keyof with generics: it turns an object type into the union of its keys.
type User = { id: number; name: string; email: string };
type UserKey = keyof User; // "id" | "name" | "email"typeof has a second job in TypeScript. In a type position (after a : or in a type declaration), it reads the type of a value. Combined with as const, it lets values be the source of truth.
const config = {
apiUrl: "https://api.example.com",
retries: 3,
features: { search: true, chat: false },
};
type Config = typeof config;
// { apiUrl: string; retries: number; features: { search: boolean; chat: boolean } }
type FeatureName = keyof typeof config.features; // "search" | "chat"Do not confuse it with the JavaScript typeof operator in an expression, which returns a string like "object" at runtime. Same word, two meanings, depending on where it appears.
Indexed access types
T["key"] looks up the type of a property, like reading a value with brackets. You can index with a union, and [number] gets the element type of an array.
type User = { id: number; name: string; roles: ("admin" | "member")[] };
type Id = User["id"]; // number
type IdOrName = User["id" | "name"]; // number | string
type Role = User["roles"][number]; // "admin" | "member"
const SIZES = ["sm", "md", "lg"] as const;
type Size = (typeof SIZES)[number]; // "sm" | "md" | "lg"This is how you reach into deep generated types (an API client's response, say) without retyping them.
T?type Order = { items: { sku: string; qty: number }[] };
type T = Order["items"][number]["qty"];Mapped types
A mapped type builds an object type by looping over keys: { [K in Keys]: ... }. It is a for...of for types. Here is how Partial and Readonly are really defined:
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
// Modifiers can be removed with a minus sign:
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };You can also transform the values. A common one turns every field of a form into an error message slot:
type SignupForm = { email: string; password: string; age: number };
type FormErrors<T> = { [K in keyof T]?: string };
// { email?: string; password?: string; age?: string }
type Validators<T> = { [K in keyof T]: (value: T[K]) => string | null };
// { email: (value: string) => ...; age: (value: number) => ... }Press Run (⌘ Enter) to see what happens.If you add a name field to SignupForm, validators stops compiling until you add a validator for it. The mapped type keeps the two in sync.
Conditional types and infer
A conditional type chooses between two types based on a test: T extends U ? X : Y. Read extends here as "is assignable to".
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hi">; // "yes"
type B = IsString<42>; // "no"Inside the test, infer declares a type variable that TypeScript fills in by pattern matching. This is how ReturnType and Awaited work:
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type ElementOf<T> = T extends (infer E)[] ? E : never;
type Unwrap<T> = T extends Promise<infer V> ? V : T;
type R = MyReturnType<() => boolean>; // boolean
type E = ElementOf<string[]>; // string
type V = Unwrap<Promise<number>>; // number"If F looks like a function returning something, call that something R, and give me R."
Distributive conditionals
When the checked type is a bare type parameter and you pass a union, the condition runs once per member and the results are joined. That is called distribution, and it is how Exclude works.
T is a bare type parameter, so the conditional distributes over a union.
X?type ToArray<T> = T extends unknown ? T[] : never; type X = ToArray<string | number>;
Template literal types
Types can be built from strings with the same backtick syntax as JavaScript template literals. With unions, every combination is generated. Built-in helpers Uppercase, Lowercase, Capitalize and Uncapitalize transform them.
type Size = "sm" | "md" | "lg";
type Color = "red" | "blue";
type ClassName = `btn-${Color}-${Size}`;
// "btn-red-sm" | "btn-red-md" | ... (6 members)
type EventName = "click" | "focus" | "change";
type HandlerProp = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus" | "onChange"Template literal types pair well with as const arrays, so the runtime list and the type come from one place:
Press Run (⌘ Enter) to see what happens.Combine them with mapped types and key remapping (as) to generate whole APIs from one list:
type Events = { login: { userId: number }; logout: undefined };
type Handlers = {
[E in keyof Events as `on${Capitalize<E & string>}`]: (payload: Events[E]) => void;
};
// { onLogin: (payload: { userId: number }) => void; onLogout: (payload: undefined) => void }E & string is there because keyof can include number and symbol keys, and Capitalize only accepts strings.
Key remapping with as
The Handlers example above used key remapping: an as clause after the key in a mapped type (TypeScript 4.1+). The loop still walks the original keys, but as decides what each output key is called. That one clause gives you three powers.
Rename keys. Generate getter names, event prop names or environment variable names from one source type:
type User = { id: number; name: string; isAdmin: boolean };
type Getters<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
};
// { getId: () => number; getName: () => string; getIsAdmin: () => boolean }Filter keys. If the as clause produces never, the key is dropped. This is how you pick keys by the type of their value, which Pick cannot do:
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
type StringFields = PickByValue<User, string>; // { name: string }
// Drop "private" keys by naming convention
type Public<T> = { [K in keyof T as K extends `_${string}` ? never : K]: T[K] };
type Row = { id: number; title: string; _rev: string; _cache: unknown };
type PublicRow = Public<Row>; // { id: number; title: string }Before 4.1 people wrote this as two steps: a mapped type that turned unwanted values into never, then an indexed access to collect the surviving keys, then Pick. You will still see that older shape in libraries. It does the same job.
Map over things that are not keys. The in part can loop over any union, including a union of objects, as long as as turns each member into a valid key. This turns a discriminated union of events into a handler table, with each handler receiving exactly its own event type:
Press Run (⌘ Enter) to see what happens.Notice the cast in dispatch. Without it, handlers[event.type](event) fails with "Argument of type 'AppEvent' is not assignable to parameter of type 'never'". TypeScript sees a union of three functions and a union of three events, but it does not track that the type and the handler are correlated, so it demands an argument that would satisfy all three handlers at once: the intersection, which is never. This is a known limit, often called the correlated union problem. A single, well-commented cast inside the dispatcher is the normal fix; the handler table itself stays fully checked.
T?type Settings = { theme: string; fontSize: number; beta: boolean; lang: string };
type T = { [K in keyof Settings as Settings[K] extends string ? never : K]: Settings[K] };A real one: DeepPartial
Partial only goes one level deep. Settings objects and test fixtures often need every level optional. A recursive mapped type with a conditional does it:
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};
type Settings = { theme: { mode: "light" | "dark"; accent: string }; lang: string };
const override: DeepPartial<Settings> = { theme: { accent: "pink" } }; // OKEvery advanced type you will meet is these pieces combined: loop over keys, test with a conditional, extract with infer, build strings with template literals.
What does this print?
type Handler<E extends string> = `on${Capitalize<E>}`;
const name: Handler<"click"> = "onClick";
const parts = name.split(/(?=[A-Z])/);
console.log(parts.length, parts[1]);Match the type syntax to its name.
infer with constraints
Plain infer captures whatever matches. Since TypeScript 4.7 you can add a constraint right where you capture: infer N extends number. If the captured piece does not satisfy the constraint, the condition fails and you get the false branch. Inside template literal types (4.8+), the constraint does something more useful: it parses the text.
type ToNumber<S> = S extends `${infer N extends number}` ? N : never;
type A = ToNumber<"42">; // 42 (a number literal, not a string)
type B = ToNumber<"abc">; // never
type C = ToNumber<"007">; // number (does not round-trip, so you get plain number)
type Port<S> = S extends `${string}:${infer P extends number}` ? P : never;
type P = Port<"localhost:3000">; // 3000
type ParseBool<S> = S extends `${infer B extends boolean}` ? B : never;
type T = ParseBool<"true">; // trueTypeScript only gives you the literal when the text converts back to exactly the same string. "007" would print as "7", so it falls back to number. Typed routers use this trick to turn "/users/:id" params into types, and config libraries use it to read "8080" as a number.
The constraint also works with tuples, where it saves a second conditional:
type FirstString<T> = T extends [infer H extends string, ...unknown[]] ? H : never;
type X = FirstString<["a", 1]>; // "a"
type Y = FirstString<[1, "a"]>; // never: the first element is not a stringWithout the constraint you would write T extends [infer H, ...unknown[]] ? (H extends string ? H : never) : never. Same result, more nesting.
Out?type Version<S> = S extends `v${infer Major extends number}.${string}` ? Major : never;
type Out = Version<"v18.2.1">;Variadic tuple types
A tuple type fixes the length and the type at each position, like [string, number]. Variadic tuple types (TypeScript 4.0+) let you spread a generic tuple inside another: [...A, ...B]. That means you can type functions that add, remove or reorder arguments without losing any of the types.
type Concat<A extends unknown[], B extends unknown[]> = [...A, ...B];
type C = Concat<[string, number], [boolean]>; // [string, number, boolean]
type Tail<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
type Last<T extends unknown[]> = T extends [...unknown[], infer L] ? L : never;
type T1 = Tail<[1, 2, 3]>; // [2, 3]
type T2 = Last<[1, 2, "z"]>; // "z"The payoff comes with real functions. Function parameter lists are tuples to TypeScript, so a generic ...rest: Rest captures the remaining parameters, names included. Here is a typed partial application helper, the kind of thing you find in middleware and logging code:
Press Run (⌘ Enter) to see what happens.Two details make this work. First, writing the parameter as [...A] instead of A asks TypeScript to infer a tuple rather than an array, so ["ada", 36] becomes [string, number] and not (string | number)[]. Second, toAda("Hi") is a compile error, because Rest is exactly [subject: string, urgent: boolean].
Labelled tuple elements make these readable in editor tooltips and errors. They change nothing at runtime:
type SliceArgs = [start: number, end: number, step?: number];
type WithRequestId<T extends unknown[]> = [requestId: string, ...args: T];
// Add a trailing argument to any function type
type WithTag<F extends (...args: any[]) => any> =
(...args: [...Parameters<F>, tag: string]) => ReturnType<F>;This is how libraries type pipe, compose, Function.prototype.bind, and event emitters where emit("save", id, draft) checks each argument against the event's payload tuple.
What does this print?
function prepend<T, Rest extends unknown[]>(head: T, rest: [...Rest]): [T, ...Rest] {
return [head, ...rest];
}
const t = prepend("id", [1, true]);
console.log(t.length, typeof t[2]);Performance: when type-level code slows the editor
Everything in this lesson runs inside the compiler, and the compiler runs every time you type. On a big codebase, clever types are a common reason autocomplete takes seconds and CI type checks take minutes. Seniors know where the costs hide.
Unions multiply. A template literal type with several unions produces every combination. ${Digit}${Digit}${Digit}${Digit} with ten digits is 10,000 members and still works. Add a fifth digit and you get "Expression produces a union type that is too complex to represent", because TypeScript caps unions at about 100,000 members. Long before that cap, big unions make every assignment check slower, since each check may compare against every member.
Recursion has limits. Recursive conditional types hit "Type instantiation is excessively deep and possibly infinite" (error 2589) at a fairly shallow depth. If the recursive call is in tail position (the branch returns the recursive call directly, not wrapped in another type), TypeScript 4.5+ evaluates it in a loop and allows up to 1,000 levels. A counter type like BuildTuple<999> compiles; BuildTuple<1200> does not. If you see error 2589, the fix is usually to restructure for tail recursion or to stop computing that type at all.
Intersections and deep generics are re-checked often. An interface is resolved once and cached by name; a big intersection of object types (A & B & C) can be flattened and compared again at each use. The TypeScript team's own performance guide recommends interface ... extends over large intersections for this reason.
Annotate return types at boundaries. If an exported function returns a giant inferred type, every caller recomputes and prints it. An explicit return type is computed once and makes errors shorter.
To find the slow spots, measure instead of guessing:
npx tsc --noEmit --extendedDiagnostics # check time, types created, instantiationsnpx tsc --noEmit --generateTrace trace # a trace you can open in a performance viewerA high "Instantiations" count points at generic or conditional types being expanded too often. The native compiler in TypeScript 7 makes the whole check much faster, but it does not change the limits above: an exponential type is still exponential. Check the TypeScript wiki's performance page for the current list of tracing tools.
Event handler names
React props name event handlers onClick, onChange, onSubmit. A template literal type can describe that pattern exactly:
type HandlerName<E extends string> = `on${Capitalize<E>}`;
type T = HandlerName<"click">; // "onClick"Write the runtime function that matches the type:
function handlerName<E extends string>(event: E): `on${Capitalize<E>}`Upper-case only the first character and leave the rest as is. An empty event name gives "on".
Deep merge with DeepPartial
App settings are nested objects. A user override only lists what it changes, at any depth. Its type is a recursive mapped type:
type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };Write deepMerge(base, patch) that returns a new object:
- For each key in
patch: if both the base value and the patch value are plain objects (not arrays, notnull), merge them recursively. - Otherwise the patch value replaces the base value (arrays are replaced, not merged).
- Keys only in
baseare kept.
deepMerge({ theme: { mode: "dark", accent: "blue" }, lang: "en" }, { theme: { accent: "pink" } })
→ { theme: { mode: "dark", accent: "pink" }, lang: "en" }- typeof (type position)
- Gets the static type of a value, as in
type Config = typeof config. - mapped type
{ [K in Keys]: ... }: builds an object type by looping over keys. Basis of Partial, Readonly, Record.- conditional type
T extends U ? X : Y: picks a type based on assignability.- infer
- Declares a type variable inside a conditional type, filled in by pattern matching.
- distributive conditional
- A conditional on a bare type parameter runs once per union member, and the results are unioned.
- template literal type
- A string type built with backtick syntax, like `
on${Capitalize<E>}`. - key remapping
- An
asclause in a mapped type that renames each key, or drops it by producingnever. - variadic tuple type
- A tuple that spreads a generic tuple inside it, like
[...A, ...B], used to type argument lists. - correlated union problem
- TypeScript cannot link a union key to the matching union handler, so the call needs one cast.