Sub topic 1
TypeScript Literal Types and Unions
Prerequisites
Assume you know basic TypeScript types, function annotations, object literals, and JavaScript switch statements.
Literal types: types that hold exactly one value
A literal type describes one exact value rather than a broad category. For example, "up" is a string literal type, 200 is a numeric literal type, and true is a boolean literal type.
type Direction = "up";
type StatusCode = 200;
type Enabled = true;
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
// move("down"); // ErrorThe parameter accepts only the value represented by Direction. Literal types are useful when a value has a small, known set of valid choices.
Combining literals into unions
A union type combines alternatives with |. A union of literals restricts a value to one member of that set.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
move("diagonal"); // ErrorThis restriction moves an error from runtime to compile time. Editors can also offer completion for the permitted values.
Why `let` and `const` infer different types
TypeScript widens inferred literal types when a variable can be reassigned. A let variable therefore usually becomes string, while a const variable keeps its exact string literal type.
let direction = "up"; // string
const fixedDirection = "up"; // "up"
direction = "down"; // OK
// fixedDirection = "down"; // ErrorObject properties are mutable by default, so their values also widen:
const config = { mode: "dark" }; // mode: stringKeeping literal types with `as const`
An as const assertion preserves literal values and marks object properties and arrays as readonly.
const config = { mode: "dark" } as const;
// type: { readonly mode: "dark" }
// config.mode = "light"; // ErrorUse it when a value is intended to be fixed and its exact values should contribute to type checking.
Exercise
What type does let color = "red" usually infer, and how can you preserve the literal type "red" in an object?
Show answer
It usually infers string. Write const color = "red" for a standalone value, or use { color: "red" } as const for an object.