Last active
November 25, 2021 18:54
-
-
Save FlorianWendelborn/f9824d334aa9804b00427a66f27c968a to your computer and use it in GitHub Desktop.
DeepObjectPartial<T>: Deep Partial, but Only Objects are Optional
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ExampleType = { | |
a: string | |
b: { | |
x: string | |
y: number | |
} | |
c: string[] | |
} | |
type ExtractOptionalKeys<TYPE> = { [KEY in keyof TYPE]: TYPE[KEY] extends Record<string, any> ? (TYPE[KEY] extends Array<any> ? never : KEY) : never }[keyof TYPE] | |
type DeepObjectPartial<TYPE extends Record<string, any>> = { | |
[KEY in ExtractOptionalKeys<TYPE>]?: DeepObjectPartial<TYPE[KEY]> | |
} & Omit<TYPE, ExtractOptionalKeys<TYPE>> | |
export const a: DeepObjectPartial<ExampleType> = { | |
a: 'wow', | |
c: ['a'] | |
} | |
export const b: DeepObjectPartial<ExampleType> = { | |
a: 'wow', | |
b: { | |
x: 'wow', | |
y: 1 | |
}, | |
c: [] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be tested on TypeScript Playground
Designed to work in TS 4.3.5 and 4.5.2