4 min read
•Question 4 of 48easyWhat are Union Types in TypeScript?
Understanding union types and type narrowing.
What You'll Learn
- What union types are
- How to use them
- Type narrowing
Union Types
A union type allows a value to be one of several types, using the | operator.
code.tsTypeScript
// Variable can be string or number
let id: string | number;
id = "abc"; // OK
id = 123; // OK
id = true; // Error!Function Parameters
code.tsTypeScript
function printId(id: string | number) {
console.log("ID:", id);
}
printId(101); // OK
printId("abc123"); // OKType Narrowing
code.tsTypeScript
function printId(id: string | number) {
if (typeof id === "string") {
// TypeScript knows id is string here
console.log(id.toUpperCase());
} else {
// TypeScript knows id is number here
console.log(id.toFixed(2));
}
}Literal Types
code.tsTypeScript
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction) {
console.log("Moving", direction);
}
move("up"); // OK
move("north"); // Error!