In TypeScript, a
union type allows a variable to have more than one possible type. It is defined using the vertical bar `|` to separate the different types that are allowed. For example:
let myVariable: number | string;
This declaration specifies that `myVariable` can be either a `number` or a `string`. This can be useful in situations where a function or method can accept arguments of multiple types.
Here's an example of a function that accepts a union type as a parameter:
function printId(id: number | string) {
console.log(`ID is ${id}`);
}
printId(101); // Output: ID is 101
printId("abc"); // Output: ID is abc
In this example, the `printId` function accepts an argument of type `number | string`, which means it can accept either a `number` or a `string` as its parameter. The function then simply logs the value of the `id` parameter to the console.
Union types can be combined with other TypeScript features like type guards and conditional types to write more complex and robust code.