Type Assertion in TypeScript

Type Assertion allows us to override the compiler determined type in our code. It is something similar to type casting in other languages. except that it does not restructure or modify the type in any way. The Type Assertion in TypeScript is a compile-time feature.

Using Type Assertion

Type Assertion is a very useful feature. There are many instances where Typescript may not be able to infer the type correctly. Usually happens when you are calling a method from a third party library. It may be Your own old JavaScript code, where you have not yet updated the Type.

For Example, consider the following code. The getPerson returns the Person as object. But we know it is of type of Person. But, as we try to access the firstName or lastName compiler throws an error.

We can solve this problem by using Type Assertions. There are two syntax’s by which you can use Type Assertion. One is as syntax and the other one is angle bracket syntax.

as syntax

The as syntax as shown below. The TypeScript treats whatever returned by the getPerson() method as Person. Hence the errors disappear.

The above code translates as follows. As you can see as Person is not in the final code as it is not supported by Javascript.

angle-bracket syntax

Here we use the type name inside the <> and place it in front of the type, which we want to assert as shown in example below.

When to use Type Assertion

Option to Assert Types is a very useful addition to the TypeScript. But use it carefully. Always define the types correctly so that you do not have to assert the types. But there may be a few use cases, where you cannot avoid them.

One of the use cases is to handle DOM events or elements. For Example, the document.getElementById returns HTMLElement. You can cast it HTMLButtonElement as shown below.

You may also assert the type when you use a third-party library. Another instance when you may need it is when your codebase has a lot of legacy JavaScript code.

References

  1. Basic Types
  2. Advanced Type

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top