在 TypeScript 中, Partial<Type> 类型可以将一个给定类型的所有属性都变为可选。但是有时我们需要将深层嵌套的对象中的属性也变为可选。这时候可以使用递归 Partial。
以下是一个递归 Partial 的示例代码:
1 2 3 4 5 6 7
| type RecursivePartial<T> = { [P in keyof T]?: RecursivePartial<T[P]>; };
type RecursivePartial2<T> = { [P in keyof T]?: T[P] extends Object? RecursivePartial2<T[P]> : T[P]; };
|
这个代码将会递归地将一个对象中的所有属性变为可选。
例如,若有如下数据结构:
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface Person { name: string; age: number; address: { street: string; city: string; country: { name: string; code: number; }; }; }
|
使用递归 Partial:
1 2
| type OptionalPerson = RecursivePartial<Person>;
|
得到的数据结构为:
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface OptionalPerson { name?: string; age?: number; address?: { street?: string; city?: string; country?: { name?: string; code?: number; }; }; }
|
现在,OptionalPerson 中的所有属性都是可选的,包括嵌套的属性。