TypeScript allows us to use more than one data type for a variable or a function parameter, and this concept is called union type. A union type enables us to define a variable with multiple types using the pipe ('|
') symbol.
Syntax :
(type1 | type2 | type3 | .. | typeN)
Example,
let myVar : string | number; //Variable with union type declaration
myVar = 256; //OK
myVar = 'Maddy'; //OK
myVar = true; //Error - boolean not allowed
Here, the myVar variable can hold both string and number, allowing flexibility to use both data types.