Union types allow a variable to hold values of different types. They're defined with the pipe |
.
// Defining a union type
type ID = string | number;
function printID(id: ID) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(2));
}
}
Use unions in API responses or helpers where inputs may be one of several types.