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

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

egghead
egghead
~ 35 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today