TypeScript type assertion

Through type assertion, you can tell the compiler, “Believe me, I know what I am doing”, you will know the detailed information of a certain value better than TypeScript, you clearly know that an entity has a more precise type than its existing type Types of.

When I first came into contact with type assertion, I didn’t understand it. Later, I learned that the reason is “type assertion is more like type selection, not type conversion.” I found that many blog posts referred to type assertion as type conversion, which caused me some troubles at the beginning.

There are two ways to use type assertions.

  1. <type> value
  2. value as type

Angle bracket syntax

let someValue: any = "this is a string";


let strLength: number = (<string>someValue).length;

As syntax

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

Leave a Reply