Last active
September 7, 2024 02:54
-
-
Save gomezcabo/dff1d95fd1eb354f686d6606a511d7da to your computer and use it in GitHub Desktop.
Typescript RecursiveRequired generic type
This file contains hidden or 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 RecursiveRequired<T> = Required<{ | |
[P in keyof T]: T[P] extends object | undefined ? RecursiveRequired<Required<T[P]>> : T[P]; | |
}>; | |
type ExampleType = { | |
a?: number; | |
b: number; | |
c?: { | |
d?: { | |
e?: number; | |
f: boolean; | |
g?: { | |
h: string | |
} | |
} | |
} | |
} | |
type ExampleTypeRequired = RecursiveRequired<ExampleType> | |
const data: ExampleTypeRequired = { | |
a: 1, | |
b: 1, | |
c: { | |
d: { | |
e: 1, | |
f: false, | |
g: { | |
h: 'hello' | |
} | |
} | |
} | |
} |
You’re welcome!
appreciate it
Thanks! 🤗
thanks for your gist!!!
Inspired by you, implemented using the -?
operator.
type RequiredDeep<T> = {
[P in keyof T]-?: T[P] extends object | undefined ? RequiredDeep<T[P]> : T[P];
};
Supports function
export type DeepRequired<T> = T extends Function
? T
: T extends object
? {
[P in keyof T]-?: DeepRequired<T[P]>
}
: T
was looking for this, thanks @gomezcabo!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This also works with arrays, which comes in handy in my case.
Thanks for the gist!