Last active
October 12, 2023 14:20
-
-
Save ReVoid/61b369dbea60e19a8a8e445ea74bc514 to your computer and use it in GitHub Desktop.
How to get a totally not nullable object
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
// Unreliable object π± | |
type UnsafePerson = { | |
name?: string | null, | |
age?: number | null, | |
} | |
// Nested unreliable object π±π±π± | |
type UnsafeParent = UnsafePerson & { child: UnsafePerson }; | |
// 1. Remove undefined with -? operator | |
// 2. Use the builtin utility NonNullable to remove null from union | |
type SafeEntity<T extends object> = { [Key in keyof T]-?: T[Key] extends object ? SafeEntity<T[Key]> : NonNullable<T[Key]> } | |
type SafePerson = SafeEntity<UnsafePerson>; // { name: string; age: number; } π | |
type SafeParent = SafeEntity<UnsafeParent>; // { name: string; age: number; child: { name: string; age: number; } } π |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment