AI Hints
Home›TypeScript Tutorial›Literal and Discriminated Unions
TypeScript · Lesson 34 of 120

Literal Types

Exact values.

⏱ 2 min read▶ Video at 26:53🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

A literal type is one exact value. Combine a few with a vertical bar, and you get a small set of allowed values. Like order statuses, packing, shipped, or delivered.

Literal Types
From the video: Literal Types
  • One exact value
  • A small set
  • Order statuses

Only the allowed values

Status allows exactly three strings. Setting it to shipped is fine. Setting it to lost is rejected. Run it. Typos are caught too.

app.tstypescript
type Status = "packing" | "shipped" | "delivered";

let status: Status = "packing";
status = "shipped";
status = "lost";
Output
app.ts line 5: Type '"lost"' is not assignable to type 'Status'.

Why literals help

Your editor suggests only the allowed values. Typos become errors. And functions can be sure they handle every possible value.

keyvalue
Editorsuggests values
Typoserrors
Functionsknow every case
Cheaper thanplain strings

Summary

Literal types allow only exact values, perfect for statuses and options. Next, discriminated unions.

Key takeaways
  • 'packing' | 'shipped'
  • Typos caught
  • Suggestions
Next up: Discriminated Unions — a kind field