In TypeScript, we can define a variable which can have multiple types of values. In other words, TypeScript can combine one or two different types of data (i.e., number, string, etc.) in a single type, which is called a union type. Union types are a powerful way to express a variable with multiple types. Two or more data types can be combined by using the pipe ('|') symbol between the types.
(type1 | type2 | type3 | ........ | type-n)
let value: number|string; value = 120; console.log("The Numeric value of a value is: "+value); value = "Welcome to rookienerd"; console.log("The String value of a value is: "+value);
In function, we can pass a union type as a parameter. We can understand it from the below example.
function display(value: (number | string)) { if(typeof(value) === "number") console.log('The given value is of type number.'); else if(typeof(value) === "string") console.log('The given value is of type string.'); } display(123); display("ABC");
TypeScript allows passing a union type to an array. We can understand it from the below example.
let arrType:number[]|string[]; let i:number; arrType = [1,2,3,4]; console.log("Numeric type array:") for(i = 0;i
Enums are used to create types that contain a list of constants. By default, enums have index values (0, 1, 2, 3, etc.). We can see the enums in the following example, which contains the list of colors.
export enum Color {RED, BLUE, WHITE}
Instead of enums, we can use union types and can get similar benefits in a much shorter way.
export type Color = 'red' | 'white' | 'blue'; const myColor: Color = 'red'; console.log(myColor.toUpperCase());