Union in TypeScript

In some cases, we can not determine whether the variable or an array will be in which type, and in that case, separated by a pipe we can make a multi-type variable or array.
But using the union we can not assign a multi-type value at a time, for that we have to replace all the values at the same time during assignment or updation.

Union Variable:

We can assign multiple types to a variable separated by a pipe.

Example of union type variable:
var sample_veriable:number|string;
sample_veriable = 10;
console.log(sample_veriable);
sample_veriable = 'Hellow World!';
console.log(sample_veriable);

Union Array

We also can make multiple types of element values using union but at the same time all the types of elements must have to same.

Example of Union Array:
var sample_arr:string[]|number[]; 
sample_arr = [1,2,4,5] ;  

var i:number; 

for(i = 0;i<sample_arr.length;i++) { 
   console.log(sample_arr[i]) ;
}  

sample_arr = ["abcd","efgh","ijkl","mnop"] 

for(i = 0;i<sample_arr.length;i++) { 
   console.log(sample_arr[i]) ;
} 

Union Function Parameters

We can also pass some union type of variables through a function also.

Example of Union Function Parameters:
function fn_name(param:string|number[]){
	if(typeof param == "string"){
		console.log('The string is: ' + param);
	}else{
		var i:number; 
		for(i = 0;i<param.length;i++) { 
		   console.log(param[i]) ;
		} 
	}
}
fn_name('Code Mystery');

Share The Post On -