Type assertion in typescript explanation with example

Published by admin on

TypeScript type assertion explanation with example

Type assertion in typescript is used to set the type of a variable and tell the compiler not to infer this. Suppose, you are switching from JavaScript to TypeScript and you know the type of one variable, you can tell the typescript compiler that this is the type this variable will have and you shouldn’t do any more type checking for it. This is called “type assertion”. Type assertion is used for compile-time checks. You can set type of one variable as number, string or any other type. For example :

let otherVar: any = "hello";
let myVar: any = 12;
myVar = otherVar as string;

console.log(typeof (myVar));

In this example, otherVar is of type any. We are setting the value of otherVar to myVar and also we are using as string to tell the compiler that the type of otherVar is string always. This program will print string as the type of myVar. It is because we are assigning the value of otherVar to myVar and also we informed the compiler that the type of otherVar is string.

 

Type assertion using angle bracket :

We can do type assertion using as operator as shown above or we can use one angle bracket <> for type assertion. Angle bracket for the above example :

let otherVar: any = "hello";
let myVar: any = 12;
myVar = <string>otherVar;

console.log(typeof (myVar));

It will also print the type as string.

 

Type assertion with objects :

Type assertion is useful with objects. For example :

{}

This is an empty object. If it can hold different properties, we can’t directly assign these properties like below :

let emptyObj = {};
emptyObj.firstVar = "Hello";
emptyObj.secondVar = "World";

It will throw one compiler time error because the compiler doesn’t know anything about the properties firstVar and secondVar.

We can create one interface and use Type assertion to change the type of the object :

interface ObjType {
    firstVar: string;
    secondVar: string;
}
let emptyObj = <objtype>{};

emptyObj.firstVar = "Hello";
emptyObj.secondVar = "World";

Now, the compiler will not show any error.

The only drawback is that if you forget to add any variable of the defined type, the compiler will not throw any error. You can also use as like below :

let emptyObj = {} as ObjType;

Even for this method, the compiler will not show any error if you forget to add any variable to the object. If you want to get autocomplete, you can so something like below :

let emptyObj: ObjType = {
    firstVar: "Hello",
    secondVar: "World",
} 

It will show one compile-time message if any one of the two variables is missed.

Categories: typescript

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *