Open In App

What is Type Assertion in TypeScript ?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Type Assertion is another way of telling the TypeScript compiler about the type of value a variable is going to store. You can assert the type of the variable by using type assertion. It is simply another way of explicitly typing the variables. It can override the automatic or default type assertion done by the TypeScript compiler. Type Assertion can be done in the following ways:

  • Using angle brackets: You can assert a type by defining it between the angle brackets.
  • Using as keyword: You can also assert type using the as keyword in TypeScript.

Example: The below code uses both methods to assert types in TypeScript.

Javascript




const cmpny: string =
    "GeeksforGeeks";
const angleAssert: number =
    (<string> cmpny).length;
const asAssert: number =
    (cmpny as string).length;
console.log(angleAssert, asAssert);


Output:

13 13

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads