Ever heard of the never keyword in TypeScript and know when to use it?
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
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.
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:
Contrast this to when we handle our function appropriately.
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.
- 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.
- You can play with the examples shown, in this TypeScript Playground.
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)