TypeScript Union
In TypeScript, we can define a variable which can have multiple types of values. In other words, TypeScript can combine one or two different types of data (i.e., number, string, etc.) in a single type, which 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 combined by using the pipe (‘|’) symbol between the types.
Syntax
Example
Output:
The Numeric value of the value is: 120 The String value of the value is: Welcome to Tutor Aspire
Passing Union Type in Function Parameter
In function, we can pass a union type as a parameter. We can understand it from the below example.
Example
Output:
The given value is of type number. The given value is of type of string.
Passing Union Type to Arrays
TypeScript allows passing a union type to an array. We can understand it from the below example.
Example
Output:
Numeric type array: 1 2 3 4 String type array: India America England
The 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.). We can see the enums 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