In TypeScript, a union type variable is a variable which can store multiple type of values (i.e. number, string etc).
A union type allows us to define a variable with multiple types. The union type variables are defined using the pipe (
'|') symbol between the types.
1. Union Type Syntax
To define a union type, use the 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 union type in TypeScript.
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.
Happy Learning !!