Skip to content

Instantly share code, notes, and snippets.

@ReVoid
Last active October 12, 2023 14:20
Show Gist options
  • Save ReVoid/61b369dbea60e19a8a8e445ea74bc514 to your computer and use it in GitHub Desktop.
Save ReVoid/61b369dbea60e19a8a8e445ea74bc514 to your computer and use it in GitHub Desktop.
How to get a totally not nullable object
// 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