What is Type Assertions in TypeScript?

In TypeScript, type assertion instructs the TypeScript compiler to treat a value as a specified type. Type assertion works similar to typecasting, but it does not do type checking or restructuring of data.

The typecasting comes with runtime support in Java, whereas type assertion in TypeScript has no impact on runtime.

A type assertion is also known as type narrowing. It allows you to narrow a type from a union type.

In TypeScript, we can do type assertion in two ways:

  • Using Angular Bracket <>
  • Using as keyword

Type assertion using as keyword

If we try to assign a name to an empty user object, TypeScript will not allow us to do it.

  let user = {};
  user.name = "Joe"; //  Property 'name' doesn?t exist on type '{}'  
  user.age = 25;     //  Property 'age' doesn?t exist on type '{}'  

In the above case we can try the type assertion like below:

  interface IUser {
    name: string;
    age: number;
  let user = {} as IUser;
  user.name = "Joe";
  user.age = 25; 

When to use Type Assertion in TypeScript?

When we use TypeScirpt, we should define the types properly so that we can avoid using type assertion. There will be cases where we will need type assertion.

One of the good use cases of type assertion is to handle DOM events or elements. We can easily asset into HTMLButtonElement from HTMLElement using type assertion.

const buttonElement = document.getElementById("inputElm") as HTMLButtonElement ;