Generic Constraints and never
What you'll learn: How TypeScript uses never to signal when generic type constraints are violated or impossible to satisfy.
The Core Idea
When you write a generic function with an extends constraint, you're setting rules about what types are allowed. If someone tries to use a type that violates those rules, TypeScript doesn't just throw a simple error—it sometimes resolves parts of the type to never. This serves as a type-level signal that something is fundamentally incompatible or impossible.
Think of never like a mathematical impossibility. When you constrain a generic to string but pass number, TypeScript may produce never in conditional checks or return positions, indicating "this path cannot logically exist."
How It Appears in Practice
Constraint Violations in Conditional Types
When you combine generic constraints with conditional types, never emerges when the condition can never be true:
type OnlyStrings<T extends string> = T extends string ? T : never;
type A = OnlyStrings<"hello">; // "hello"
type B = OnlyStrings<42>; // Error: Type 'number' does not satisfy constraint 'string'
Here, 42 fails the constraint before the conditional even runs. But consider:
type FilterStrings<T> = T extends string ? T : never;
type C = FilterStrings<"hello">; // "hello"
type D = FilterStrings<42>; // never (no error, just resolves to never)
Without the constraint, never becomes the result when the type doesn't match.
Empty Intersections
When constraints create impossible intersections, you get never:
type BothStringAndNumber<T extends string & number> = T;
// T must be BOTH string AND number simultaneously
// This constraint itself is 'never' - impossible to satisfy
type Result = BothStringAndNumber<any>; // Error: no type satisfies this
Distributive Filtering
Constraints combined with distributive conditionals use never to filter out non-matching types:
type ExtractNumbers<T> = T extends number ? T : never;
type Numbers = ExtractNumbers<1 | "hello" | 2 | false>;
// Distributes: (1 extends number ? 1 : never) | ("hello" extends number ? "hello" : never) | ...
// Result: 1 | never | 2 | never
// Simplifies to: 1 | 2
Here, never acts as a removable element in unions—types that failed the constraint simply vanish.
Why This Matters
The never type is TypeScript's way of saying "this combination is impossible under your constraints." Rather than silently accepting bad types or only showing errors, never becomes part of the type algebra, enabling sophisticated type-level logic where invalid paths self-eliminate.
Key Takeaway: When generic constraints cannot be satisfied, TypeScript produces never as a type-level proof that the combination is impossible—allowing impossible branches to collapse in unions and signaling constraint violations in type computations.