TypeScript Union Types
Union Types allow variables to be set to multiple types using the pipe (|) operator. The variable can then be assigned values based on the specified types.
Note: Only the specified types can be assigned; assigning other types will result in an error.
The syntax for creating a union type is as follows:
Type1|Type2|Type3
Example
Declare a union type:
TypeScript
var val: string|number
val = 12
console.log("Number is " + val)
val = "tutorialpro"
console.log("String is " + val)
Compiling the above code yields the following JavaScript code:
JavaScript
var val;
val = 12;
console.log("Number is " + val);
val = "tutorialpro";
console.log("String is " + val);
The output is:
Number is 12
String is tutorialpro
Assigning a different type will result in an error:
var val: string|number
val = true
Union types can also be used as function parameters:
TypeScript
function disp(name: string|string[]) {
if (typeof name == "string") {
console.log(name)
} else {
var i;
for (i = 0; i < name.length; i++) {
console.log(name[i])
}
}
}
disp("tutorialpro")
console.log("Output array....")
disp(["tutorialpro", "Google", "Taobao", "Facebook"])
Compiling the above code yields the following JavaScript code:
JavaScript
function disp(name) {
if (typeof name == "string") {
console.log(name);
}
else {
var i;
for (i = 0; i < name.length; i++) {
console.log(name[i]);
}
}
}
disp("tutorialpro");
console.log("Output array....");
disp(["tutorialpro", "Google", "Taobao", "Facebook"]);
The output is:
tutorialpro
Output array....
tutorialpro
Google
Taobao
Facebook
Union Type Arrays
Arrays can also be declared as union types:
TypeScript
var arr: number[]|string[];
var i: number;
arr = [1, 2, 4]
console.log("**Number Array**")
for (i = 0; i < arr.length; i++) {
console.log(arr[i])
}
arr = ["tutorialpro", "Google", "Taobao"]
console.log("**String Array**")
for (i = 0; i < arr.length; i++) {
console.log(arr[i])
}
Compiling the above code yields the following JavaScript code:
JavaScript
var arr;
var i;
arr = [1, 2, 4];
console.log("**Number Array**");
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
arr = ["tutorialpro", "Google", "Taobao"];
console.log("**String Array**");
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
The output is:
**Number Array**
1
2
4
**String Array**
tutorialpro
Google
Taobao