Skip to content

Instantly share code, notes, and snippets.

@gomezcabo
Last active May 9, 2025 15:13
Show Gist options
  • Save gomezcabo/dff1d95fd1eb354f686d6606a511d7da to your computer and use it in GitHub Desktop.
Save gomezcabo/dff1d95fd1eb354f686d6606a511d7da to your computer and use it in GitHub Desktop.
Typescript RecursiveRequired generic type
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'
}
}
}
}
@gomezcabo
Copy link
Author

@gomezcabo Yes, that does the trick nicely! Thanks!

Just for my own academic curiosity, do you know why the TS compiler was saying 'string' is not assignable to type 'DeepRequired<keyof T>'? It seems like they should be compatible.

I guess when passing down the keyof T to the generic, this one could be string, number or symbol and that's where the Type was failing. No way to determine which one of those. That's why the fix was to include the check T[K] extends PropertyKey (PropertyKey === string | number | symbol).

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