Skip to content

Instantly share code, notes, and snippets.

@FlorianWendelborn
Last active November 25, 2021 18:54
Show Gist options
  • Save FlorianWendelborn/f9824d334aa9804b00427a66f27c968a to your computer and use it in GitHub Desktop.
Save FlorianWendelborn/f9824d334aa9804b00427a66f27c968a to your computer and use it in GitHub Desktop.
DeepObjectPartial<T>: Deep Partial, but Only Objects are Optional
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: []
}
@FlorianWendelborn
Copy link
Author

FlorianWendelborn commented Nov 25, 2021

Can be tested on TypeScript Playground

Designed to work in TS 4.3.5 and 4.5.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment