Union in TypeScript

Till now we have seen variable declaration with one data type, or we can declare a variable with any data type so that we can store values of any data type in that. We use UNION if we want to restrict the data type of variable to two or more data types.
We combine two or more data types using pipe symbol (|) to denote a Union type.
Syntax

var variable:type1|typ2|type3|...

Below is an example

var empID:number|string;
empID = 1001;
console.log("Emp ID as number: " + empID);
empID = "EMP1001";
console.log("Emp ID as string: " + empID);

Below is the output of above code

You can also pass union type in function parameters and can also use in Arrays.
Below is an example of passing Union as Parameter

var empID:number|string;
empID = 1001;
console.log("Passing number");
check(empID);
empID = "1001";
console.log("\nPassing String");
check(empID);
function check(EID:number|string):void{
    if(typeof(EID)=="number"){
        var nextEID = EID+1;
        console.log("Next Employee ID will be: " + nextEID)
    }
    else{
        console.log("Data Type is: " + typeof(EID));
    }
}

Below is the output of above code

Below is an example of Union in Arrays

var empID:number[]|string[];
empID = [10,20,30];
console.log("Display Numbers");
displayArray(empID);

empID = ["Delhi","Mumbai","Pune"];
console.log("\nDisplay String");
displayArray(empID);

function displayArray(EIN:number[]|string[]):void{
    var i:number;
    for(i=0; i<EIN.length; i++){
        console.log(EIN[i]);
    }
}

Below is the output of above code

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started