Skip to content
Related Articles

Related Articles

Explain Type assertions in TypeScript

Improve Article
Save Article
  • Last Updated : 07 Mar, 2022
Improve Article
Save Article

In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn’t reconstruct code. You can use type assertion to specify a value’s type and tell the compiler not to deduce it. When we want to change a variable from one type to another such as any to number etc, we use Type assertion. 

We can either use <> angular brackets or as keywords to do type assertion. When we migrate code from typescript to another language type assertion comes into play. Runtime support comes with typecasting, whereas type assertion has no effect on runtime. It is used by the compiler. 

Example 1: Type assertion using syntax

In this example, we give assign the ‘geeksforgeeks’ string to a variable of type unknown. We further assign the value of the string to another variable and calculate the length of the string. In the below code we have asserted that str is of type number by using the “as” keyword. 


let str: unknown = "geeksforgeeks";
let len: number = (str as string).length;



Example 2: Type assertion using <> angle brackets syntax

This example is similar to the before one, we assign a number to a variable of type any and then assign the value to another variable and we have asserted that the num variable is of type “Number”. We used <> angle brackets instead of keywords.


let num: any = 77;
// Conversion from any to number
let num1 = <Number> num;
console.log(typeof num1);



Example 3: Type assertion for objects

We may occasionally encounter a circumstance in which an object is defined without any properties. The compiler throws an error as a result of this. However, we may prevent this issue by utilizing type assertion. With the help of the following example, we can comprehend it.


interface details {}
details.first_name = "Sarah";
details.last_name = "jane";


error TS2693: 'details' only refers to a type, but is being used as a value here.
details.first_name = "Sarah";

After defining parameters, the compiler doesn’t throw an error. Compiler raises an error in the before example as it cannot find any properties within the object. Type assertion helps us resolve such errors. We used type assertion on details.


interface details {
    first_name: string;
    last_name: string;
let person_1 = <details>{};
person_1.first_name = "Sarah";
person_1.last_name = "jane";


{ first_name: 'Sarah', last_name: 'jane' }


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!