Skip to content

Instantly share code, notes, and snippets.

@gomezcabo
Last active April 19, 2024 01:52
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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'
}
}
}
}
@heyzling
Copy link

heyzling commented Mar 2, 2024

This also works with arrays, which comes in handy in my case.

type ExampleType = {
  a: number;
  b: {name:string}[]
}

type ExampleTypeRequired = RecursiveRequired<ExampleType>

declare const exampleData: ExampleTypeRequired;

exampleData.b[0].name // always: string, no warnings

Thanks for the gist!

@gomezcabo
Copy link
Author

You’re welcome! ☺️

@Sans3108
Copy link

appreciate it

@gomezcabo
Copy link
Author

Thanks! 🤗

@rambo-panda
Copy link

rambo-panda commented Apr 19, 2024

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];
};

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