TypeScript Master (50 Qs)•Part 2: Advanced Type System & Metaprogramming (Mid-Level)
How do you implement a Deep Partial or Deep Readonly type?
mid LevelCode ExampletypescriptAdvanced Type System
In Simple Words:
Standard Partial<T> is shallow (only makes top-level keys optional). Using recursive conditional types, we can make every nested level optional:
typescript
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
interface NestedConfig {
database: {
connection: {
host: string;
port: number;
}
}
}
const override: DeepPartial<NestedConfig> = {
database: { connection: { port: 5432 } } // host is optional!
};