DEV Community

Ambrose Liew
Ambrose Liew

Posted on

Never Say Never, The never Keyword In TypeScript And Exhaustive Matching

Ever heard of the never keyword in TypeScript and know when to use it?

The never keyword in TypeScript

Exhaustive Matching

Exhaustive Matching is when you try to match a discriminant property to its corresponding value/function. This is better explained through an example.

Example

An example of Exhaustive Matching

The above colorToString function is an example of Exhaustive Matching. Where we try to map all enums of COLORS to a corresponding value.

The main idea of Exhaustive Matching is we try to match a set of values to another set of values (can also be functions, DOM elements, etc.).

The Problem?

The problem arises when we try to add another value to our COLORS enum.

When we update our enums, the compiler does not warn us that we have forgotten to update our colorToString function as well. Thus, we might forget to handle this newly added color.

No warning from the compiler. Even though we have added a new color.

The Solution?

Use the never keyword in TypeScript!

We can assign the color to a type of never in TypeScript. This tells the compiler to warn us if we forget to update a function that Exhaustive Matches.

Like so:

Compiler warning when we forget to update our Exhaustive Matching function

Contrast this to when we handle our function appropriately.

No warnings from the compiler when we handled all our enums

Conclusion

I hope that from these simple examples, you have learned a new tool for you! This is an especially important skill to use if you are in a large project and there are multiple such functions scattered around in the project!


A Step Further

  • You can abstract out the assert never into a function for reusability throughout your codebase.

Using a function to assert never for reusability

  • Besides coming in as a form of a switch/case statement, Exhaustive Matching functions can be in a form of if/else statements or if/return statements.

Other forms of Exhaustive Matching functions


If you felt that you have learned something new, do feel free to follow 🥰, drop a react 💖 or write a comment ✍️!
It helps makes me create and share more valuable content for you to become a better Web Developer! 🤗

Top comments (0)