Last active
January 27, 2022 16:21
-
-
Save antoniopresto/2fe27828554a5875385ebb152a26ef67 to your computer and use it in GitHub Desktop.
Typescript convert Nullable (null or undefined) to Partial / not required
This file contains 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
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; |
Author
antoniopresto
commented
Jan 27, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment