Sub topic 1
Starting point: string literal types and unions
Prerequisites
This chapter assumes basic TypeScript type aliases, string literal types, union types, and generics. A string literal type describes one exact string, while a union type describes several allowed alternatives.
String literal types and unions
type Method = "get" | "post";
type Status = "loading" | "success" | "error";
const method: Method = "get";
const status: Status = "success";
// const invalid: Method = "put"; // ErrorMethod does not mean “any string.” It means exactly "get" or "post". This precision lets the compiler check names, commands, and other fixed string values.
A template literal type builds string literal types by placing type expressions inside backticks. Its syntax resembles a JavaScript template string, but it is evaluated by the type system.
Your first template literal type
type Greeting = `Hello, ${string}`;
const first: Greeting = "Hello, world";
const second: Greeting = "Hello, TypeScript";
// const invalid: Greeting = "Hi, world"; // ErrorHere, ${string} is a placeholder. It allows any string in that position, so Greeting describes every string that starts with "Hello, ".
A literal can also be combined with a literal type:
type Direction = "up" | "down";
type Command = `move-${Direction}`;
const a: Command = "move-up";
const b: Command = "move-down";
// const c: Command = "move-left"; // ErrorCommand is equivalent to "move-up" | "move-down".
Unions expand into every combination
When more than one placeholder contains a union, TypeScript forms the cross product: every value from the first union combines with every value from the second.
type Color = "red" | "blue";
type Size = "sm" | "lg";
type ClassName = `${Color}-${Size}`;
// "red-sm" | "red-lg" | "blue-sm" | "blue-lg"
const smallRed: ClassName = "red-sm";
const largeBlue: ClassName = "blue-lg";
// const invalid: ClassName = "red-md"; // ErrorThis pattern is useful for finite naming systems, such as CSS classes, event names, and command identifiers. Keep the unions small because the number of generated combinations multiplies quickly.
Exercise
What values are allowed by type Key = ${"user" | "team"}-${"id" | "name"};?
Show answer
"user-id", "user-name", "team-id", and "team-name".