Open In App

What is Type Assertion in TypeScript ?

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:

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




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

Output:

13 13
Article Tags :