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.
Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | interface Person { firstName: string; lastName: string; } let person =getPerson(); person.firstName=""; //Property 'firstName' does not exist on type '{}'. person.lastName=""; //Property 'lastName' does not exist on type '{}' //Some third Party Library or some old Javascript Code function getPerson() { return {} } |
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.
1 2 3 4 5 6 | let person = getPerson() as Person; person.firstName=""; //OK person.lastName=""; //OK |
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.
1 2 3 4 5 | var person = getPerson(); person.firstName = ""; person.lastName = ""; |
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.
1 2 3 4 5 6 | let person = <Person> getPerson(); person.firstName=""; //OK person.lastName=""; //OK |
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.
1 2 3 4 5 6 7 8 | var btn = document.getElementById("btn") as HTMLButtonElement ; function btnClickEvent($event:Event) { let e = $event as MouseEvent; } |
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.