Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.