TypeScript Union
Last Updated :
03 Feb, 2023
The TypeScript union has the ability to combine one or two different types of data (i.e., number, string, float, double, etc). It is the most powerful way to express a variable with multiple types. Use pipe (‘|’) symbol to combine two or more data types to achieve Union type.
Syntax:
(type1|type2|type3|...|type-n)
Example:
let value: number | string;
value = 190;
console.log( "Numeric value of the value: " + value);
value = "Welcome to TypeScript!" ;
console.log( "String value of the value: " + value);
|
Compiling the above code to generate the following JavaScript code.
let value: number | string;
value = 190;
console.log( "Numeric value of the value: " +value);
value = "Welcome to TypeScript!" ;
console.log( "String value of the value: " +value);
|
Output:
190
Welcome to TypeScript!
Example: In this example the geeks is of union type, denoted using (string | number). So, we can assign a string or a number to it nothing else is allowed.
let geeks: (string | number);
geeks = 123;
geeks = "XYZ" ;
geeks = true ;
|
Function Parameter as Union Type: We can pass the function as a parameter. In this example, parameter geeks is of union type. You can pass either a string value or a number value otherwise the compiler will give an error.
Example:
function displayType(geeks: (string | number)) {
if ( typeof (geeks) === "number" )
console.log( 'geeks is number.' )
else if ( typeof (geeks) === "string" )
console.log( 'geeks is string.' )
}
displayType(49);
displayType( "GFG" );
displayType( true );
|
Array as Union Type: In union type we can also pass an array. The program declares an array. The array can represent either a numeric collection or a string collection.
Example:
var arr = [2, 5, 7, 5, 11, 15];
console.log( "Display the array elements" );
for ( var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
arr = [ "Geeks" , "G4G" , "GFG" , "GeeksforGeeks" ];
console.log( "Display the array elements" );
for ( var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
|
Output:
Display the array elements
2
5
7
5
11
15
Display the array elements
Geeks
G4G
GFG
GeeksforGeeks
Union can Replace enums: It is a list of constant types that is created by Enums. By default, enums have index values (0, 1 ,2, 3, etc). Enums are actually transpiled (taking source code written in one language and transforming into another language that has a similar level of abstraction) and end up into the result like JavaScript.
Share your thoughts in the comments
Please Login to comment...