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.
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.
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.