Post

TypeScript: Exhaustiveness Checking

TypeScript's Exhaustiveness Checking helps catch missing cases in switch statements.

TypeScript: Exhaustiveness Checking
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. Normal

It looks perfect. But what happens if a new color type (black) is added during code maintenance? TS Error

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?

Never 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. Add

You can use this method not only with switch statements but also with if statements. If

3. Be Cautious!

This is a Compile Time error! It just notifies you that you missed the logic. It cannot catch errors at runtime.

Runtime

This post is licensed under CC BY 4.0 by the author.