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?
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
Let's examine what the type of
action would be in the
It is of type
So, if we create a dummy function that took in a parameter of type
never that is called in the
switch branch, maybe the TypeScript compiler would error if it reached there ...
Let's add a
Reset action and give this a try:
The TypeScript compiler errors as we hoped. Neat!
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.
Originally published at https://www.carlrippon.com/make-switch-statements-super-type-safe-with-the-never-type on Sept 20, 2019.