Exhaustiveness checking — never catches the forgotten case¶
Level: 201 · for TypeScript users modelling data with unions
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: Once every member of a union has its case, what reaches default is never; assign it to a never variable there, and adding a triangle member later turns the forgotten case into TS2322 on that line, naming the triangle type.
Keywords: exhaustiveness checking, never
What the finished page will answer¶
- What does tsc report at
const forgotten: never = shapeafter atrianglemember is added and nocasehandles it? - Why does a function with return type
numberreport TS2366 when itsswitchmisses a member, even without anevervariable? - Does
shape satisfies neverindefaultwork as the same check, and what does TS1360 say? - What should
defaultdo at run time when a value outside the type arrives anyway, for example fromJSON.parse? - Why does a
defaultthat returns a fallback value switch the check off, like Rust's_arm?
Examples it will need¶
-
exhaustiveness_never_tserror.ts— TS2322 naming the unhandled triangle type at theneverassignment, and TS2366 for a second function with nodefault -
exhaustiveness_runtime_fallback_ts.ts— the Error thrown by thedefaultbranch when a shape parsed from JSON has a kind the type does not list
See also¶
- Discriminated unions — the tagged union the switch walks through
any,unknownandnever— whatneveris, and why onlyneverfits into it- External data — where a value outside the union comes from
if,switchand? :—switchfall-through at run time- Rust:
matchexpressions ↗ — amatchin Rust must cover every case with no helper - Rust: The wildcard
_↗ — the catch-all arm that switches Rust's check off