Javatpoint Logo
Javatpoint Logo

TypeScript Type Assertion

TypeScript allows us to override its inferred and analyzed view of types in any way we want to. This mechanism is known as "type assertion."

In cases when TypeScript determines that the assignment is invalid, then we have an option to override the type using a type assertion. When we use a type assertion, it is guaranteeing that the assignment is valid in a scenario where the type system has found it not to be, 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 it would have a different type. This allows us to treat any as a number, or number as a string. Type assertion is commonly used when we are porting over code from JavaScript to TypeScript.

Type assertion works like typecasting, but it doesn't 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 given example, we declare 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.' So, when we were assigning empCode to employeeCode, we have asserted that empCode in a type number in this case. 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 a keyword.

Example

Type Assertion with object

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. It can be shown below.

In the above example, we created an interface Student with the properties name and code. Then, we used type assertion on the student which is a 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