This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Using Assertion to Convert Types in TypeScript

    Ari PickerAri Picker

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

    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 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.

    00:17 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.

    00:41 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.

    01:01 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.

    01:13 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.

    01:25 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.

    01:39 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.

    01:53 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.

    Discuss

    Discuss