Syntax
let value: "specific-string" | 42 | true;Examples
String and Numeric Literal Unions
Restricting a value to an exact, known set of options.
type Direction = "up" | "down" | "left" | "right";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
function move(direction: Direction) {
console.log(`Moving ${direction}`);
}
move("up"); // OK
// move("north"); // Error - not one of the allowed literalsconst Assertions
Using "as const" to infer the most specific literal type possible.
let a = "hello"; // inferred as: string (widened)
const b = "hello"; // inferred as: "hello" (literal, since const cannot be reassigned)
let config = {
mode: "production"
} as const;
// config.mode is typed as the literal "production", not string
// config.mode = "development"; // Error - as const also makes properties readonlyBest practices
- Use literal type unions instead of a general string/number type when a value only has a small, known set of valid options - it catches typos at compile time
- Use as const on object/array literals to lock in their most specific literal types, especially useful for configuration objects
- Combine literal types with discriminated unions for exhaustive, type-safe handling of different variant shapes
- Prefer literal unions over TypeScript enums for simple cases - they compile to nothing extra and integrate more naturally with plain JavaScript
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook