Sub topic 11
Recursive Types such as DeepReadonly and Awaited
This chapter assumes you know mapped types, conditional types with extends, and the infer keyword. You should also be comfortable with generics and with the keyof operator. Recursive types apply these tools to a value that contains more values of the same shape, such as nested objects or wrapped promises.
Why recursion is needed
A mapped type transforms only the top level of an object. Readonly<T> marks ui as readonly, but it does not touch ui.theme. To handle every level, the mapped type must refer to itself for each property. TypeScript allows this when the reference sits inside an object type, which delays evaluation until a property is read.
Awaited: unwrapping promises
A conditional type can call itself when the result is not yet known. Awaited removes nested Promise wrappers:
type MyAwaited<T> = T extends Promise<infer U> ? MyAwaited<U> : T;
type P = MyAwaited<Promise<Promise<number>>>; // number
type Q = MyAwaited<string>; // stringThe infer U captures the wrapped type. If U is another promise, the type calls MyAwaited again. The recursion stops when the input is no longer a promise.
DeepReadonly: walking an object tree
DeepReadonly applies readonly at every depth:
type DeepReadonly<T> = T extends (...args: any[]) => any
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
type Settings = { ui: { theme: string }; tags: string[] };
type Frozen = DeepReadonly<Settings>;
// { readonly ui: { readonly theme: string }; readonly tags: readonly string[] }The three branches run in this order:
- Functions return unchanged. A function is also an object, so without this check the mapped type would turn it into a plain object and lose its call signature.
- Other objects get a mapped type that marks each key readonly and recurses into each value.
- Primitives such as
stringandnumberreturn unchanged, which ends the recursion.
The array case works because a homomorphic mapped type over an array produces a readonly array.
Limits to watch for
Recursive types on circular data can loop forever. An object that refers to itself, such as a parent pointer, makes DeepReadonly expand without end. Also, DeepReadonly marks Date and Map values as readonly object shapes, which can break code that calls their methods. Add branches for those types when your data includes them.
Exercise
Why does DeepReadonly check for function types before checking for object types?
Show answer
Functions are objects in TypeScript. If the object branch ran first, a function type would be mapped into an object with readonly keys, and its call signature would be lost. Checking functions first returns them unchanged.