Lesson

TypeScript Literal Types

10 min reading
Free Course

TypeScript Literal Types: Locking Variables to Exact Values

A literal type narrows a broad primitive like string or number down to one exact value, such as "north" or 200. On their own, single literal types look strict, but combining them into unions creates crisp, self-documenting APIs with zero runtime overhead.

Instead of accepting any arbitrary string for an alignment or HTTP method, literal unions catch typos like "centr" immediately in your editor.

String, Numeric, and Boolean Literal Unions

You can combine string literals, numeric literals (like HTTP status codes or dice rolls), and boolean literals cleanly.

type Alignment = "left" | "center" | "right";
type DiceFace = 1 | 2 | 3 | 4 | 5 | 6;

function alignBox(text: string, align: Alignment): string {
  return `[${align.toUpperCase()}] ${text}`;
}

function rollFixed(): DiceFace {
  return 4;
}

console.log(alignBox("Header", "center"), rollFixed());

Literal Inference Inside Objects with as const

When passing an object field into a function expecting a literal type, const opts = { align: "center" } fails because TypeScript widens opts.align to string. Fix it with as const (const opts = { align: "center" } as const) or annotate const opts: { align: Alignment } = { align: "center" }.

Common Mistakes to Avoid

  • Passing let variables to literal parameters: let dir = "left"; widens to string, so passing dir to Alignment fails unless declared with const or typed : Alignment.
  • Duplicating literal unions across multiple files: Export one shared type Alignment = ... or derive the type from a const ALIGNMENTS = ["left", "center", "right"] as const array (typeof ALIGNMENTS[number]) so runtime validation and types never drift.
  • Confusing true literal type with boolean: Typing a field ok: true inside a discriminated union means that branch only matches ok === true.

Frequently Asked Questions

How do I get both a runtime array of options and a literal union type without duplicating?

Write const SIZES = ["sm", "md", "lg"] as const; type Size = (typeof SIZES)[number];. You get autocomplete for "sm" | "md" | "lg" plus the runtime SIZES array for <select> dropdowns.

Are literal types faster or lighter than TypeScript enums?

Yes. Literal unions emit zero runtime JavaScript code, whereas standard enums emit lookup objects.

Can I combine literal types with template literals?

Yes. type EventName = on${Capitalize<"click" | "hover">}`` produces "onClick" | "onHover" automatically.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum