46

Make switch statements super type safe with the never type

 4 years ago
source link: https://www.tuicool.com/articles/B7Z7Rzj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
mUbYzen.jpg!web Photo by Wendelin Jacober  from  Pexels

The problem

The following code is a simple reducer for a counter component. It contains a switch statement over a union type which is pretty type safe:

How can we make this even more type safe? What if we get a new requirement for the counter to be reset? That would mean that a new action is added to the Actions type. When we add the new action, how can we get the TypeScript compiler to remind us that a new branch in the switch statement needs to be implemented?

The solution

What if we could tell the TypeScript compiler that the default branch in the switch statement should never be reached? Well we can do just that with the never type!

Let’s examine what the type of action would be in the default branch:

BjMNz2y.png!web

It is of type never !

So, if we create a dummy function that took in a parameter of type never that is called in the default switch branch, maybe the TypeScript compiler would error if it reached there …

Let’s add a Reset action and give this a try:

yqqQFje.png!web

The TypeScript compiler errors as we hoped. Neat!

Wrap up

Calling a dummy function that has a parameter of type never is neat way to get the TypeScript compiler to warn us if an area of our program is reached that shouldn’t be. It’s a nice touch in a switch statement over a union type so that we are reminded to implement an additional branch if the union type is ever changed.

Marius Schulz has a great post on the never type if you want to learn more about it.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK