Lesson 6 of 10
Covering every case
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
A forgotten case stops the build
Explanation
A switch might cover every case of a union today, and then tomorrow a teammate adds a new case and default quietly swallows it. No error, no warning, and every wallet payment ends up with a fee of zero.
The compiler narrows the type with each case. Once you've covered every case, nothing is left, and the type of the value in default becomes never, the type that has no values. Pass that value to a function that only accepts never, and any forgotten case stays in the type and becomes a compile error.
A helper declared as function assertNever(x: never): never protects you twice. At compile time it only accepts a type with nothing left in it, and at runtime it throws if data nobody expected ever reaches it.
Your task
Write assertNever so it throws an error, and call it in the default branch of fee instead of return 0. The build will stop there, so fix it by adding a "wallet" case whose fee is 1% of amount.
Checks
6 checks- No type errors
- The wallet fee is 1% of the amount
- An unknown case throws instead of counting as zero
- The default branch in fee calls assertNever
- A switch that covers every case compiles with assertNever
- Forgetting a single case stops the build