Use Partial in a nested property with typescript

Let's say I have this type:

interface State { one: string, two: { three: { four: string }, five: string } } 

I am doing a State Partial as follows Partial<State>

But how can I make nested properties partially, for example, if I wanted to make two also partial.

How can I do it?

+16
source share
4 answers

You can easily define your own RecursivePartial type, which will make all properties, including nested ones, optional:

 type RecursivePartial<T> = { [P in keyof T]?: RecursivePartial<T[P]>; }; 

If you want some of your properties to be partial, you can use this with intersection and Pick :

 type PartialExcept<T, K extends keyof T> = RecursivePartial<T> & Pick<T, K>; 

This will make everything optional, with the exception of the keys specified in parameter K

+37
source

It is possible you can create a "deep" partial type:

 type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]>; }; 

Which can be used as serial

 const state: DeepPartial<State> = { two: { three: { four: '4' } } } 
+10
source

For TypeScript 2.8 or later, the next type should solve the problem with the Array property.

 type NestedPartial<T> = { [K in keyof T]?: T[K] extends Array<infer R> ? Array<NestedPartial<R>> : NestedPartial<T[K]> }; 

Please see the example below.

 interface Foo { NumProp: number; SubItem: Foo; SubItemArray: Foo[]; } 

Valid result with conditional type

Valid result

Invalid result

Invalid Result

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html

+3
source

Try to exclude the nested property and add it again as partial:

 interface Foo { someName: Partial<Omit<MainType, 'lvl2Partial'> & { lvl2Partial: Partial<SubType> }> } 
0
source

Source: https://habr.com/ru/post/1274236/


All Articles