Course contentsShow
← TypeScript
Lesson 466 of 1,79611. Literal TypesFree lesson

When to Use Literal Types

Identify scenarios where literal types improve type safety: status codes, HTTP methods, configurations.

When to Use Literal Types

You'll learn: Where literal types shine by preventing invalid values and enforcing precise contracts.

The Core Idea

Literal types excel when you have a fixed, known set of values that a variable can accept. Instead of allowing any string or number, you lock down exactly which strings or numbers are valid. This prevents typos, enforces business rules, and makes invalid states impossible to represent.

Think of literal types as dropdown menus for your code. Just like a form dropdown only allows selecting predefined options (not typing anything you want), literal types restrict values to an exact whitelist.

Key Scenarios

HTTP Methods

When working with web requests, there are only specific valid methods:

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";

function makeRequest(method: HttpMethod, url: string) {
  // TypeScript prevents method: "GETTT" or method: "get"
}

Status Codes

Applications often have discrete states:

type LoadingState = "idle" | "loading" | "success" | "error";
type HttpStatusCategory = 200 | 201 | 400 | 401 | 403 | 404 | 500;

Configuration Options

Settings often have specific valid choices:

type LogLevel = "debug" | "info" | "warn" | "error";
type Environment = "development" | "staging" | "production";

Why It Matters

Using string or number types here would compile, but you'd lose:

  • Autocomplete showing valid options
  • Compile-time errors catching typos like "GETT" or "develpoment"
  • Exhaustiveness checking ensuring all cases are handled

Key Takeaway: Use literal types when values come from a closed, enumerable set—especially for APIs, configurations, and state machines where invalid values should be impossible.