In TypeScript, we can define a variable which can have multiple type of values (i.e. number, string etc). This is called union type.
A union type allows us to define a variable with multiple types. This is achieved by using the pipe (
'|') symbol between the types.
1. Union Type Syntax
Use pipe symbol between multiple types which a variable should support.
let myVar: string | number; //myVar can store string and number types
2. Union Type Example
Let’s see an example of typescript union types.
let myVar : string | number; //Variable with union type declaration myVar = 100; //OK myVar = 'Lokesh'; //OK myVar = true; //Error - boolean not allowed
myVar variable can hold both
string, which allows us to have the flexibility to use both data types.
The TypeScript compiler makes sure that it alerts us if we try to assign a type of value that was not defined.
Drop me your questions in comments section.
Happy Learning !!