Literal types and type aliases
A literal type is a type with exactly one value: "north" is a type that only allows the string "north". On their own they are not much use, but in a union they make a precise set of allowed values:
let size: "small" | "medium" | "large" = "medium";
size = "huge"; // error: '"huge"' is not assignable
This catches typos at once: no more bugs from writing "meduim" somewhere.
Type aliases
type gives any type a name, so you can reuse it:
type Size = "small" | "medium" | "large";
type Point = { x: number; y: number };
function price(size: Size): number { /* ... */ return 0; }
type and interface overlap for objects. type can also name unions, tuples and other types, which interfaces cannot.
Checking every case
With a switch over a union, TypeScript knows which values are left. If every function path must return, forgetting a case is an error:
function emoji(size: Size): string {
switch (size) {
case "small": return "🐜";
case "medium": return "🐕";
case "large": return "🐘";
}
}
Add a new size to Size and TypeScript points at every switch that does not handle it yet.
Your task
- Define
type Directionas the four directions"north","south","east","west". - Define
type Positionas an object with numbersxandy. - Write
move(pos: Position, dir: Direction): Position, returning a new position one step away (north isy + 1, east isx + 1). - Fix the typo in the starter.