Exhaustiveness Checking with never
Use never to ensure all union cases are handled.
Welcome
Exhaustiveness checking uses the `never` type to ensure every case of a union is handled. When you add a new union member, TypeScript will tell you exactly where to update your code.
The Exhaustiveness Problem
When you switch on a union type and forget a case, JavaScript silently falls through. TypeScript can detect this with a never check.
type Shape = 'circle' | 'square';
function area(s: Shape): number {
if (s === 'circle') return 3.14;
if (s === 'square') return 1;
// What if we add 'triangle'?
}All lessons in this course
- typeof and Truthiness Narrowing
- instanceof and in Narrowing
- User-Defined Type Guard Functions
- Exhaustiveness Checking with never