Course Banner


TypeScript Union

So far you have learn that TypeScript is a statically types language where we can define data type of a variable. But, problem is that once you define the data type, you cannot store other value. Also the requirement may arise where we can store more than one data type values. Typescript provides this facility. You can define more than one type of data type for a single variable and then you can store multiple data types values.  

Example :

1
2
3
4
5
var student_details:string|number
student_details = 50
console.log("Roll Number of the student is :  "+student_details)
student_details = "Science"
console.log("He is studying  "+student_details)

In the above example, we have declared a variable called ‘students_details’ the variable’s type is union. Now. we have stored roll number as number and then course name as Science which are two different data types and it works fine.

Its output is as follows −

In the above example, we have used union type in the variable, but we can also use union type in function also.

Below is the example of using union type in the function.

 

Union Type and function parameter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function students(sname:string|string[]) {
  if(typeof sname == "string") {
 	console.log(sname)
  } else {
 	var i;    
 	for(i = 0;i<sname.length;i++) {
    	console.log(sname[i])
 	}
  }
}
students("Meena")
console.log("Students names are....")
students(["Rajesh","Kiran","Sudipto","Hetal"])


The output is as follows −

Union Type and Arrays

We have seen so far using union type in variable and functions. Apart from that we can also use union types with arrays, properties and interfaces.


Example: Union Type and Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
var listing:number[]|string[];
var i:number;
listing = [20,30,40]
console.log("----- List of numeric Array---") ;
for(i = 0;i<listing.length;i++) {
  console.log(list[i])
} 
listing = ["Java","PHP","ASP.NET"]
console.log("----- List of string Array---") ;
for(i = 0;i<listing.length;i++) {
  console.log(listing[i])
}

In the above program we have declared an array with data type Union Type Numeric and String.Later, we have stored numeric value in the array and displayed.

Then, in the same array we have stored string array. Then we printed it. And both worked fine

Below is the  result :


Ad Image