Sikau

TypeScript · Day 10 · about 20 min

Literal types

Exact values as types, and as const.

Only these values

A traffic light is "red", "amber" or "green" — never "purple". literal types let a type be an exact value, and unions of them make perfect "one of these choices" types.

Literal unions and as const

type Light = "red" | "amber" | "green";
let now: Light = "red";
now = "purple";

type Size = "S" | "M" | "L";
function price(size: Size): number {
  return size === "S" ? 100 : size === "M" ? 150 : 200;
}
price("XL");

const SIZES = ["S", "M", "L"] as const;
type FromList = (typeof SIZES)[number];

TypeScript also has enum, but unions of string literals are simpler, need no extra code at runtime, and are what most modern codebases prefer.

The rest of this lesson

  • Literal unions as menus of choicesexplain
  • Deriving unions from data with as constexplain
  • Will it type-check?predict
  • Widened or literal?predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript