- 4 years ago
- Afaq Arif
- 2,104 Views
-
2
In this chapter, we will discuss about Union Types in TypeScript. We will see how can we merge Union Types to arrays.
In TypeScript 1.4, you can merge one or two types of programs. We can use Union types to show the value that can be one of the many types. You can combine two or more data types to indicate a Union Type by using the pipe symbol (|). In simple, you can write union type as a sequence of types separated by vertical bars.
Syntax: Union literal
Example: Union Type Variable
var val:string|number
val = 12
console.log("numeric value of val "+val)
val = "This is a string"
console.log("string value of val "+val)
In the above example, the variable’s type is union. It means that the variable can contain either a number or a string as its value.
On composing, runs following JavaScript code.
//Generated by typescript 1.8.10
var val;
val = 12;
console.log("The numeric value of Val " + val);
val = "is a string";
console.log("The string value of Val " + val);
Its output is as follows.
The numeric value of Val 12
The string value of Val is a string
Example: Union Type and function parameter
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("mark")
console.log("Printing names array....")
disp(["Mark","Tom","Mary","John"])
The function disp() can accept argument either of the type string or a string array.
It will show following JavaScript code on composing.
//Generated by typescript 1.8.10
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("mark");
console.log("Printing names array....");
disp(["Mark", "Tom", "Mary", "John"]);
The output of the above code is as follows.
Mark
Printing names array….
Mark
Tom
Mary
John
Union Type and Arrays
You can also apply Union types to arrays, properties, and interfaces. The following shows the use of union type with an array.
Example: Union Type and Array
var arr:number[]|string[];
var i:number;
arr = [1,2,4]
console.log("**numeric array**")
for(i = 0;i<arr.length;i++) {
console.log(arr[i])
}
arr = ["Mumbai","Pune","Delhi"]
console.log("**string array**")
for(i = 0;i<arr.length;i++) {
console.log(arr[i])
}
The program states an array. The array can show either a numeric collection or a string collection.
It shows following JavaScript code on composing.
//Generated by typescript 1.8.10
var arr;
var i;
arr = [1, 2, 4];
console.log("**numeric array**");
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
arr = ["Lahore", "Karachi", "Islamabad"];
console.log("**string array**");
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Its output is as follows.
**numeric array**
1
2
4
**string array**
Lahore
Karachi
Islamabad
- 4 years ago
- Afaq Arif
- 2,104 Views
-
2