×
☰ See All Chapters

TypeScript typeof operator

TypeScript typeof operator is used to get the type of a variable as string.

Example:

 

let test: boolean ;

console.log(typeof  test); //prints boolean

 

When you have to declare a variable with the type same as the type of some other variable typeof operator can be used in variable declaration as below:

let test: string ;

let xyz: typeof  test;

xyz = 'Hello';

 

When you have to assign value based on type of variable typeof operator can be used in if condition as below:

let strOrNum: string | boolean ;

 

if(typeof strOrNum === "string") {

        strOrNum = 'Hello';

}

 

if(typeof strOrNum === "boolean") {

        strOrNum = true;

}

You can store the type of a variable for future use if you sure that type of variable will going to change. Stored type can be used later while declaring variable as below:

let test : any ;

test = 10;

type initialType = typeof test;

test = true;

let num:initialType;

num = 20;

 


All Chapters
Author