Lesson 6 of 11 · 9 min

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

  1. Define type Direction as the four directions "north", "south", "east", "west".
  2. Define type Position as an object with numbers x and y.
  3. Write move(pos: Position, dir: Direction): Position, returning a new position one step away (north is y + 1, east is x + 1).
  4. Fix the typo in the starter.
main.ts
// Define Direction and Position here


function move(pos: Position, dir: Direction): Position {
  return pos;
}

console.log(move({ x: 0, y: 0 }, "noth"));

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…