Javatpoint Logo
Javatpoint Logo

TypeScript Type Assertion

In TypeScript, type assertion is a mechanism which tells the compiler about the type of a variable. When TypeScript determines that the assignment is invalid, then we have an option to override the type using a type assertion. If we use a type assertion, the assignment is always valid, so we need to be sure that we are right. Otherwise, our program may not work correctly.

Type assertion is explicitly telling the compiler that we want to treat the entity as a different type. It allows us to treat any as a number, or number as a string. Type assertion is commonly used when we are migrating over code from JavaScript to TypeScript.

Type assertion works like typecasting, but it does not perform type checking or restructuring of data just like other languages can do like C# and Java. The typecasting comes with runtime support, whereas type assertion has no impact on runtime. However, type assertions are purely a compile-time construct and provide hints to the compiler on how we want our code to be analyzed.

Example

In the above example, we have declared a variable empCode as of type any. In the next line, we assign a value of this variable to another variable named employeeCode. Here, we know that empCode is of type number, even though we declared it as 'any.' when we are assigning empCode to employeeCode, we have asserted that empCode is of type number. Now the type of employeeCode is number.

TypeScript provides two ways to do Type Assertion. They are

  1. Using Angular Bracket <>
  2. Using as keyword

Using Angular Bracket <>

In TypeScript, we can use angular "bracket <>" to show Type Assertion.

Example

Using as Keyword

TypeScript provides another way to show Type Assertion by using "as" keyword.

Example

Type Assertion with object

Sometimes, we might have a situation where we have an object which is declared without any properties. For this, the compiler gives an error. But, by using type assertion we can avoid this situation. We can understand it with the following example.

Example

In the above example, we will get a compilation error, because the compiler assumes that the type of student is {} without properties. We can avoid this situation by using a type assertion, which can be shown below.

In the above example, we have created an interface Student with the properties name and code. Then, we used type assertion on the student, which is the correct way to use type assertion.

Next TopicTypeScript Arrays




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA