Use the never type to avoid code with dead ends using TypeScript

Share this video with your friends

Social Share Links

Send Tweet

Programming language design does have a concept of bottom type that is a natural outcome as soon as you do code flow analysis. TypeScript does code flow analysis (😎) and so it needs to reliably represent stuff that might never happen. This is what the never type is all about.

[00:00] Here, we have a function that has an infinite loop, and hence, never returns. TypeScript automatically infers the return type of such a function as never. Similarly, if a function always throws, then again, TypeScript infers the return type of such a function to be never.

[00:21] Also, if during code flow analysis, you end up with a condition that can never be true, TypeScript infers the type never. There is never any value in a never variable, and any attempt to add one will result in an error. You can use this to do exhaustive checks in union types.

[00:41] For example, let's say you have a variable returned from the server that can be a string or a number. You can easily add code that handles different cases using the JavaScript typeof operator. You can add an additional else, and assign the variable to a never to ensure that all types were eliminated.

[01:02] Later, if you need to add another type to the union, for example, a Boolean, you will now get nice errors at all the places where the new type was not handled, because only a never is assignable to a never. Now, if you go ahead and add another typeof to handle this new case, the error goes away.