Type Aliases and Union Types
A type alias gives a name to any type, so you can reuse it instead of repeating the same shape everywhere. It's functionally similar to interface for describing objects, but type can also name things interface can't, like unions.
type Point2D = { x: number; y: number };
let home: Point2D = { x: 0, y: 0 };
console.log(home);{ x: 0, y: 0 }Union types — a value that can be one of several types
A union type, written with |, means a value can be any one of the listed types. It's how TypeScript expresses "this could genuinely be either kind of value" without giving up type safety.
function formatId(id: string | number): string {
return `ID-${id}`;
}
console.log(formatId(42));
console.log(formatId("A17"));ID-42 ID-A17
Literal types
A type can also be a specific literal value rather than a whole category — a union of literals is how TypeScript expresses "one of exactly these options", similar to an enum but lighter weight.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up");
move("left");Moving up Moving left
Next: functions — typed parameters, return types, and optional and default parameters.
Practice exercise
Write a function describeValue(value: string | number): string that returns "text: " + value if value is a string, or "number: " + value if it's a number. Print describeValue("hi") and describeValue(7).