Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 986 of the free egghead.io lessons, plus get TypeScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

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

1:24 TypeScript lesson by

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.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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.

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.

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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?