In TypeScript, you can define a variable which can have multiple types 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.
Union types helps in some situations when migrating from JavaScript code to TypeScript code.
Union Type Syntax
As said earlier, use pipe symbol between multiple types which variable can support.
let myVar : string | number; //myVar can store string and number types
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
Here, the myVar
variable can hold both number
and 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 !!