Deep Partial Mapped Type
Recursively make every property optional with a mapped type, the right shape for patch updates and nested test fixtures.
Code
export type DeepPartial<T> = T extends (infer U)[]
? DeepPartial<U>[]
: T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
export interface Account {
id: string;
profile: {
name: string;
address: { city: string; zip: string };
};
}
export function applyPatch(base: Account, patch: DeepPartial<Account>): Account {
return {
...base,
...patch,
profile: { ...base.profile, ...(patch.profile ?? {}) },
};
}How it works
The working surface is the function applyPatch — everything else is wiring.
The return value is newly constructed — inputs are never handed back.
Putting it to use
The primary signature is export function applyPatch(base: Account, patch: DeepPartial<Account>)
applyPatch is what another module would consume; nothing else here is load-bearing for callers.
Core lines
? { [K in keyof T]?: DeepPartial<T[K]> }
Interactive Tools for This Topic
FAQ
- Does `applyPatch` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `applyPatch` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.