Web Analytics

Literal Types

Beginner~15 min

Literal types allow you to specify exact values a variable can have, providing precise type safety.

String Literal Types

Output
Click Run to execute your code
Literal Types: Instead of allowing any string/number, limit to specific values like "north" | "south"

When to Use Literal Types

  • Status values: "pending" | "approved" | "rejected"
  • Directions: "north" | "south" | "east" | "west"
  • Modes: "light" | "dark" | "auto"
  • Fixed values: Dice rolls (1-6), HTTP methods

Literal Types vs Enums

Feature Literal Types Enums
Syntax Simple union Enum declaration
Runtime No runtime code Generates object
Autocomplete โœ“ Yes โœ“ Yes
Best for Simple string/number sets Complex enumerations

Common Mistakes

1. Using String Instead of Literal

// โœ— Too broad - any string allowed
function setTheme(theme: string) { }

// โœ“ Precise - only specific values
function setTheme(theme: "light" | "dark") { }

2. Forgetting const Assertion

let direction = "north";  // Type: string

// โœ“ Use const or as const
const direction = "north";  // Type: "north"
let dir = "north" as const;  // Type: "north"
Best Practice: Use literal types for fixed sets of values. They provide better type safety than plain strings.

Summary

  • Literal types specify exact values
  • Works with strings, numbers, booleans
  • Combine with unions for multiple options
  • Provides autocomplete and type safety