A Union Type allows a variable to be one of several types. This is useful when a value could be more than one type, and you need to handle each type differently.
Example:
In the padLeft
function, the padding
argument is defined as either a string
or a number
.
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
console.log(padLeft("Hello world", 4)); // returns " Hello world"
The example shows how string | number
is a union type, and TypeScript helps check which type the variable is at compile-time.