Skip to content

Literal Types

Jorge Castro edited this page Nov 10, 2025 · 1 revision
type Season = "spring" | "summer" | "fall" | "winter";

This one works

const season1: Season = "spring";

This one won't work because type '"autumn"' is not assignable to type 'Season'.

const season2: Season = "autumn";`

It also works with numbers and other types

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

Literal inference

This will show an error because method is a string.

declare function handleRequest(
  url: string,
  method: "GET" | "POST" | "PUT" | "DELETE"
): void;

const request = { url: "https://example.com", method: "GET" };
handleRequest(request.url, request.method);

With a const assertion, it won't show the error

const request = { url: "https://example.com", method: "GET" as const };
handleRequest(request.url, request.method);

Clone this wiki locally