×
☰ See All Chapters

TypeScript Union Types

In TypeScript you can make variable to accept values of different types by creating union type. To do this, while declaring a variable you have to declare all the data types that variable should accept. All the data type should have vertical bar ( | ) between them.

TypeScript Union Types Example

let strOrNum: string | boolean ;

After this declaration, strOrNum can be assigned with number or string value, but not a value of any other type. This is shown in the following code.

strOrNum = "Hello"; // Acceptable

strOrNum = false; // Acceptable

strOrNum = 5; // Error - "Type is not assignable"

 

TypeScript considers the type of latest assignment. So after "Hello" assignment, type will be string till the next assignment. When value false is assigned types will be boolean. Boolean type will be preserved until next string value is assigned.

let strOrNum: string | boolean ;

strOrNum = "Hello";

console.log(typeof  strOrNum); //prints string

strOrNum = false;

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

strOrNum = 'Hi';

console.log(typeof  strOrNum); //prints string

 

 


All Chapters
Author