What is TypeScript – Union

TypeScript allows us to use more than one data type for a variable or a function parameter. This is called union type.Syntax:

(type1 | type2 | type3 | .. | typeN)

Consider the following example of union type.Example: Union Copy

let code: (string | number);
code = 123;   // OK
code = "ABC"; // OK
code = false; // Compiler Error

let empId: string | number;
empId = 111; // OK
empId = "E111"; // OK
empId = true; // Compiler Error

In the above example, variable code is of union type, denoted using (string | number). So, you can assign a string or a number to it.

The function parameter can also be of union type, as shown below.Example: Function Parameter as Union Type Copy

function displayType(code: (string | number))
{
    if(typeof(code) === "number")
        console.log('Code is number.')
    else if(typeof(code) === "string")
        console.log('Code is string.')
}

displayType(123); // Output: Code is number.
displayType("ABC"); // Output: Code is string.
displayType(true); //Compiler Error: Argument of type 'true' is not assignable to a parameter of type string | number

In the above example, parameter code is of union type. So, you can pass either a string value or a number value. If you pass any other type of value e.g. boolean, then the compiler will give an error.

Post Author: admin

Avatar
I am Software Engineer, Microsoft MVP for Developer Security and ASPInsider. I am regular conference speaker, frequent blogger at learnfreecoding.com and author of the OWASP Top 10 for .NET. I worked for lots of companies throughout the last decade and is keen to share my knowledge with the community. I have broad and deep knowledge of the Microsoft stack with a special interest on web technology and the cloud. for consultancy email me on info@learnfreecoding.com