TypeScript: Exhaustiveness Checking
TypeScript's Exhaustiveness Checking helps catch missing cases in switch statements.
1
2
3
4
"devDependencies": {
"ts-node": "10.9.2",
"typescript": "5.8.3"
}
1. Why is Exhaustiveness Checking needed?
Exhaustiveness Checking is a feature of TypeScript. Let’s look at the example below.
It looks perfect. But what happens if a new color type (black) is added during code maintenance?
We might not realize that we need to add a new case to handle the new type, especially if there are many lines of code. In a production environment, we might miss adding a new line in the switch case.
Exhaustiveness Checking helps prevent this situation.
2. How to use Exhaustiveness Checking?
Unlike before, the default case uses
never
. This generates a compile-time error for values that are not handled in any case.
If you use the exhaustive check pattern, you just find the TypeScript compile error and add a new case.
You can use this method not only with switch
statements but also with if
statements.
3. Be Cautious!
This is a Compile Time error! It just notifies you that you missed the logic. It cannot catch errors at runtime.