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
(type1 | type2 | type3 | ........ | type-n)
Example
snippet
let value: number|string;
value = 120;
console.log("The Numeric value of a value is: "+value);
value = "Welcome to rookienerd";
console.log("The String value of a value is: "+value);
Output
The Numeric value of the value is: 120 The String value of the value is: Welcome to rookienerd

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
snippet
function display(value: (number | string))
{
    if(typeof(value) === "number")
        console.log('The given value is of type number.');
    else if(typeof(value) === "string")
        console.log('The given value is of type string.');
}
display(123);
display("ABC");
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
snippet
let arrType:number[]|string[]; 
let i:number; 
arrType = [1,2,3,4];
console.log("Numeric type array:")  

for(i = 0;i
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.

snippet
export enum Color {RED, BLUE, WHITE}

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

Example
snippet
export type Color = 'red' | 'white' | 'blue';
const myColor: Color = 'red';
console.log(myColor.toUpperCase());
Output
RED
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +