Building NonNullable with never
What you'll learn: You'll discover how to implement TypeScript's NonNullable<T> utility type yourself using conditional types that return never to filter out null and undefined.
The Core Idea
The NonNullable<T> utility type removes null and undefined from a type T. Behind the scenes, it uses a conditional type that returns never for unwanted types. When a conditional type in a union resolves to never, that branch gets filtered out entirely — like water passing through a filter that catches debris.
How It Works
Here's the actual implementation:
type MyNonNullable<T> = T extends null | undefined ? never : T;
Let's break down what happens:
- If
Tisnullorundefined: The conditional returnsnever - Otherwise: It returns
Tunchanged - Distribution magic: When
Tis a union, this distributes over each member
Seeing It in Action
type Example1 = MyNonNullable<string | null | undefined>;
// Result: string
type Example2 = MyNonNullable<number | null>;
// Result: number
type Example3 = MyNonNullable<boolean | undefined | null>;
// Result: boolean
Why never Is the Key
When you write string | never | number, TypeScript simplifies it to just string | number. The never disappears! This is exactly what makes filtering work:
// Distribution happens like this:
// string extends null | undefined ? never : string → string
// null extends null | undefined ? never : null → never
// undefined extends null | undefined ? never : undefined → never
// Final union: string | never | never → string
Think of never as an automatic "delete this" marker in unions — TypeScript's type system removes it during union simplification.
Key Takeaway: NonNullable<T> leverages conditional types with never returns to filter unwanted types from unions, using distribution to check each union member individually and eliminate null and undefined branches.