← Back to TypeScript Course | Chapter 5: Type Aliases and Union Types | Lesson 4 of 9

Literal Types

Literal types allow a variable to contain one exact value instead of any value of a broader type. They are useful for creating precise sets of allowed strings, numbers, or booleans.

String Literal Types

A string literal type represents one single, exact string value, such as the type admin rather than the general type string. Combining several string literals with a union, like admin | editor | viewer, creates a controlled, closed set of allowed choices.

Example: String Literal Types

typescript
type Role = 'admin' | 'editor';
let role: Role = 'admin';
console.log(role);

Number Literal Types

Number literal types work the same way for numbers, restricting a value to one or more specific exact numbers rather than any number at all. They're especially handy when only a small, fixed set of numeric options is actually valid, like HTTP status codes.

Example: Number Literal Types

typescript
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 4;
console.log(roll);

Boolean Literal Types

Boolean literal types can restrict a value to exactly true or exactly false as its own distinct type, rather than the general boolean type that allows either. This is less common day-to-day but can be useful when modeling a specific, fixed object state.

Example: Boolean Literal Types

typescript
type AlwaysTrue = true;
let flag: AlwaysTrue = true;
console.log(flag);

Literal Types in Functions

Literal types in function parameters prevent callers from passing any value outside a specific, supported set, catching typos and unsupported options at compile time instead of at runtime. They also give editors enough information to offer precise autocomplete suggestions for valid values.

Example: Literal Types in Functions

typescript
function setAlign(value: 'left' | 'center' | 'right') {
  console.log(`Aligned: ${value}`);
}
setAlign('center');

Literal Types with Type Aliases

Pairing a literal union with a type alias, like type Theme = light | dark, makes that set of allowed values reusable across variables, functions, and object properties throughout a codebase. This is a common and effective pattern for representing application states and fixed configuration options.

Example: Literal Types with Type Aliases

typescript
type Theme = 'light' | 'dark';
let theme: Theme = 'dark';
console.log(theme);
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.