Recursive types
Relay’s config is nested: config.queue.retry.attempts. Two things need to treat it as a whole
tree. Environments override parts of it, naming only the fields they change. And after loading,
nobody may mutate it. Partial<Config> and Readonly<Config> only touch the top level, so
config.queue.retry.attempts = 9 still compiles.
The fix is a type that applies itself to each property. A type can refer to its own name, and that is recursion. It is the same idea as a recursive function: a case that stops, and a case that calls itself on something smaller.
A type that contains itself
Section titled “A type that contains itself”JSON is the classic example. A JSON value is a primitive, an array of JSON values, or an object whose values are JSON values:
type Json = string | number | boolean | null | Json[] | { [key: string]: Json }
const payload: Json = { source: "github", tags: ["push", "main"], retries: null }
// @ts-expect-error: a function is not JSONconst bad: Json = { run: () => {} }// @ts-expect-error: undefined is not JSONconst missing: Json = { value: undefined }Use Json for data from JSON.parse or for a webhook body you store without looking inside.
It is better than unknown when you want to say “this can be serialized”.
Recursion in a mapped type
Section titled “Recursion in a mapped type”To go deeper, a mapped type calls itself on each property’s type:
type DeepReadonly<T> = T extends (...args: never[]) => unknown ? T : T extends readonly (infer U)[] ? readonly DeepReadonly<U>[] : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> } : T
interface Config { server: { host: string; port: number } queue: { retry: { attempts: number } } sources: string[]}
declare const config: DeepReadonly<Config>
// @ts-expect-error: readonly at every depthconfig.queue.retry.attempts = 9// @ts-expect-error: arrays become readonly arraysconfig.sources.push("stripe")The conditional type has the cases a recursive function would have. A function is returned
as is: mapping over a function type would turn it into {}. An array becomes a readonly array of
the same element type, made deep. Any other object is mapped. Everything else, the primitives, is
the base case and stops the recursion.
The order matters. An array is an object, so the array check must come before the object
check, or arrays would be mapped key by key.
DeepPartial for overrides
Section titled “DeepPartial for overrides”DeepPartial has the same shape with ? instead of readonly. Arrays stay whole, because an
override that lists sources means “use this list”, not “merge it with the base”:
type DeepPartial<T> = T extends readonly unknown[] ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T
interface Config { server: { host: string; port: number } queue: { retry: { attempts: number; baseDelayMs: number } }}
const staging: DeepPartial<Config> = { queue: { retry: { attempts: 5 } } }
// @ts-expect-error: port is a number at any depthconst bad: DeepPartial<Config> = { server: { port: "80" } }Note what the type does not do. It describes an override. Applying it still takes code, and the
honest way to write mergeConfig for a three-field-deep config is field by field with ??:
interface Config { server: { host: string; port: number }}type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T
function mergeConfig(base: Config, override: DeepPartial<Config>): Config { return { server: { host: override.server?.host ?? base.server.host, port: override.server?.port ?? base.server.port, }, }}A generic deep merge that returns T would need a cast inside, because the compiler cannot see
that a loop over keys rebuilds exactly T. A cast in a library is fine. A cast in a 20-line config
module is a bug waiting for a new field. Typed by hand, a new field is a compile error until
mergeConfig handles it.
One more use. Relay’s CLI reads --set server.port=8080. A type for the valid paths turns a typo
into a compile error:
type Paths<T> = T extends readonly unknown[] ? never : T extends object ? { [K in keyof T & string]: T[K] extends object ? K | `${K}.${Paths<T[K]>}` : K }[keyof T & string] : never
interface Config { server: { host: string; port: number } sources: string[]}
type ConfigPath = Paths<Config>// "server" | "server.host" | "server.port" | "sources"
const ok: ConfigPath = "server.port"// @ts-expect-error: no such pathconst typo: ConfigPath = "server.prot"The mapped type builds one entry per key, and [keyof T & string] turns the entries into a union
of their values. The template literal from lesson 4 joins the key to the
paths below it.
Limits
Section titled “Limits”The compiler stops recursion at a fixed depth, about 50 levels when the recursive call is not in tail position. Tail-recursive conditional types (TypeScript 4.5 and later) go much further, to roughly 1000 levels. Past the limit it reports “Type instantiation is excessively deep and possibly infinite”. Config-sized trees are far from that. A type that recurses over a long string or a big union can reach it, and then it fails in confusing ways.
Exercise
Section titled “Exercise”The starter’s DeepReadonly and DeepPartial do nothing at depth, Paths is string, and
mergeConfig ignores its override. Make the types recursive so the type tests pass, then merge
the override into the base.
- A type may refer to itself:
Jsonis made ofJson. The recursion needs a case that stops. DeepReadonlyandDeepPartialare mapped types that call themselves on each property. Check functions and arrays before the general object case.- A type describes an override, it does not apply it. Write
mergeConfigfield by field, so a new config field is a compile error until the merge handles it. Paths<T>turns a typo in a dotted path into a compile error.- Recursion costs compile time and error-message length, and the compiler stops at a fixed depth.
Further reading
Section titled “Further reading”- TypeScript 4.1: template literal types, key remapping and recursive conditional types.
- TypeScript 4.5: tail-recursion elimination and
Awaited.