Deep partial
- TypeScript course
- Advanced
- Lesson 11/57
- 4 min
Learn the deep Partial pattern.
What is deep partial?
DeepPartial, unlike normal Partial, also makes all fields of nested objects optional. It is written by combining a mapped type and a conditional type: for each field, if it is an object, DerinPartial is applied recursively. This makes deeply nested configuration type-safe.
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object
? DeepPartial<T[K]>
: T[K];
};Object check with conditional
In DeepPartial, the condition T[K] extends object checks whether the field is an object. If it is, DerinPartial<T[K]> is applied recursively; otherwise the value is made optional as-is. This way primitive fields are preserved while nested objects are processed deeply.
Practice Write and use DeepPartial
Define a recursive mapped type named DerinPartial: <T> = { [K in keyof T]?: T[K] extends object ? DerinPartial<T[K]> : T[K] }. The Ayarlar interface should contain baslik: string and alt: { renk: string }. The p variable should be of type DerinPartial<Ayarlar> with value { baslik: "test", alt: { renk: "mavi" } }. Print p.alt.renk with console.log.
Starter code
// DerinPartial adinda recursive mapped type tanimla
// her alan opsiyonel olsun, nesne ise recursive uygulansin
// Ayarlar interface tanimla
// p nesnesini DerinPartial ile tanimla
// p.alt.renk yazdirSample solution
type DerinPartial<T> = {
[K in keyof T]?: T[K] extends object ? DerinPartial<T[K]> : T[K];
};
interface Ayarlar {
baslik: string;
alt: { renk: string; };
}
const p: DerinPartial<Ayarlar> = { baslik: "test", alt: { renk: "mavi" } };
console.log(p.alt.renk);Expected output
mavi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between DeepPartial and normal Partial?
- Takes no type parameter
- Runs faster
- Makes only numbers optional
- Also makes nested object fields optional Correct answer
Explanation: Partial only makes top-level fields optional; DeepPartial recursively descends into nested objects and makes all fields optional.
2 Recursive DerinPartial call
type DerinPartial<T> = {
[K in keyof T]?: T[K] extends object ? ____<T[K]> : T[K];
};
type DerinPartial<T> = {
[K in keyof T]?: T[K] extends object ? DerinPartial<T[K]> : T[K];
};
Explanation: DeepPartial calls itself recursively for nested objects; it is applied to the child object via DerinPartial<T[K]>.
3 DeepPartial concepts
| Term | Meaning |
|---|---|
Partial<T> |
Only top level |
DerinPartial<T> |
Nested optional |
keyof T |
Keys of T |
extends object |
Object check |