Files
code-snippets/docs/typescript/string-literal-types.md
Liam Pietralla 4ce86b1532
All checks were successful
Build, Test & Publish / Build (pull_request) Successful in 25s
Build, Test & Publish / Build and Publish Container Image (pull_request) Has been skipped
Build, Test & Publish / Deploy to Infrastructure (pull_request) Has been skipped
added ts string literal types
2025-08-15 13:23:35 +10:00

646 B

String Literal Types

String literal types are a powerful feature in TypeScript that allows you to specify exact string values a variable can hold. This is useful for creating more precise types and can help catch errors at compile time.

Example

const DIRECTIONS = ["left", "right", "up", "down"] as const;
type Direction = typeof DIRECTIONS[number];

// Usage
function move(direction: Direction) {
  // ...
}

// Array Usage
for (const dir of DIRECTIONS) {
  move(dir);
}

In the above examples you can see how we can both use the Direction type directly and also leverage the DIRECTIONS array for type-safe values.