Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

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


    Using Assertion to Convert Types in TypeScript


    Sometimes the compiler needs help figuring out a type. In this lesson we learn how to help out the compiler with Typescript type assertion.



    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




    We have a superhero and a bad guy. Let's make a function that saves the day if the function's argument is a superhero, and a commits a bad deed if its argument is a bad guy. Our function needs to accept something that could be a superhero or a bad guy.

    The IDE is telling us something's wrong. Let's see what compiler says. Something doesn't have powers. This is because the compiler is evaluating both types of the union-type argument. Since the bad guy doesn't have powers, something doesn't have powers. We can get a hold of the superhero's power's property by asserting that something is a superhero.

    An assertion is how we told the compiler, "We have some information about something's type that it doesn't." There are two different syntaxes for assertion. We're using the as type syntax, which goes behind the value. We're putting something in parens in order to isolate it from its property. If we remove the parens we can't make the assertion.

    The other syntax is with angle brackets, and it goes before the value. The angle bracket syntax was the original syntax, but it conflicted with JSX, so the as type syntax was created.

    Type assertions are compile-time assertions. This means that the assertion is only valid at compile time. Once the code is compiled with JavaScript, the type assertion no longer exists, because JavaScript doesn't have type assertions.

    Let's finish our if block by calling the superhero saves the day method. We need to add the else block. Let's call our function with both types. Let's see if it works.

    To review, we used TypeScript's type assertions when we need to tell the compiler that we know more about something's type than it does. They can be written with the as type syntax or the angle bracket syntax unless you're using JSX.

    If we need to assert something while referencing its property, we can isolate it in parens. TypeScript type assertions are compile-time assertions, meaning that the assertion only exists at compile time or in your IDE. Once the code is compiled with JavaScript, the assertion is gone.