Skip to content

Instantly share code, notes, and snippets.

@antoniopresto
Last active January 27, 2022 16:21
Show Gist options
  • Save antoniopresto/2fe27828554a5875385ebb152a26ef67 to your computer and use it in GitHub Desktop.
Save antoniopresto/2fe27828554a5875385ebb152a26ef67 to your computer and use it in GitHub Desktop.
Typescript convert Nullable (null or undefined) to Partial / not required
export type NullableToPartial<T> = T extends { [K: string]: any }
? {
[K in keyof ({
[K in NullableKeys<T>]?: T[K];
} & {
[K in RequiredKeys<T>]-?: T[K];
})]: ({
[K in NullableKeys<T>]?: T[K];
} & {
[K in RequiredKeys<T>]-?: T[K];
})[K];
}
: never;
export type NullableKeys<T> = Extract<NullableByKind<T, 'nullable'>, string>;
export type RequiredKeys<T> = Extract<NullableByKind<T, 'required'>, string>;
export type NullableByKind<T, Kind extends 'nullable' | 'required'> = {
[K in keyof T]?: IsNullable<T[K]> extends (
Kind extends 'nullable' ? true : false
)
? K
: never;
}[keyof T] extends infer Temp
? Temp extends undefined
? never
: Temp
: never;
@antoniopresto
Copy link
Author

Screen Shot 2022-01-27 at 12 58 23

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