How do you write a type that recursively converts every property of a nested object type to be optional, using conditional types alongside mapped types?
Short answer
Combine a mapped type (to iterate keys) with a conditional type (to check if each property's value is itself an object, and recurse if so) — this lets you deep-partial an arbitrarily nested object type, unlike the built-in Partial which only affects the top level.
Advertisement
AModel answer
Combine a mapped type (to iterate keys) with a conditional type (to check if each property's value is itself an object, and recurse if so) — this lets you deep-partial an arbitrarily nested object type, unlike the built-in Partial<T> which only affects the top level.
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
interface Config { server: { host: string; port: number }; }
type PartialConfig = DeepPartial<Config>;
// { server?: { host?: string; port?: number } }Real-world example
Typing a configuration-merging function that accepts partial overrides at any nesting level, not just the top level.
Likely follow-ups
- Why does the built-in Partial<T> utility type NOT recurse into nested objects by default?
Related topics