Javatpoint Logo
Javatpoint Logo

TypeScript Union

In TypeScript, we can define a variable that can have multiple types of values. In other words, TypeScript has the ability to combine one or two different types of data (i.e., number, string, etc.). This is called a union type. Union types are a powerful way to express a variable with multiple types. Two or more data types can be achieved by using the pipe ('|') symbol between the types.

Syntax

Example

Output:

Numeric value of the value: 120
String value of the value: Welcome to JavaTpoint

Passing Union Type in Function Parameter

We can pass union type in function as a parameter. It can be shown below.

Example

Output:

Numeric value of the value: 120
String value of the value: Welcome to JavaTpoint

Passing Union Type to Arrays

We can also pass union type to an array. It can be shown below.

Example

Output:

Numeric type array:
1
2
3
4
String type array:
India
America
England

Union can Replace enums

Enums are used to create types that contain a list of constants. By default, enums have index values (0, 1 ,2, 3, etc.). Enums can be shown in the following example which contains the list of colors:

Example

Instead of enums, we can use union types and can get similar benefits in a much shorter way:

Example

Output:

RED
Next TopicTypeScript String




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA