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

String Literal Types Syntax

Learn to declare and use string literal types like 'success' or 'error' as exact type constraints.

String Literal Types Syntax

You'll learn: How to define types that accept only specific string values, creating ultra-precise type constraints.

The Core Idea

In TypeScript, you don't have to settle for broad types like string. You can create types that accept only one exact string value. These are called string literal types, and they look like this:

let status: 'success';
status = 'success'; // ✓ OK
status = 'error';   // ✗ Error: Type '"error"' is not assignable to type '"success"'

Notice the quotes inside the type annotation? That's a string literal type. The variable status can only hold the exact string 'success' — nothing else.

Why This Matters

String literal types are incredibly useful for values that have a fixed set of options, like status codes, directions, or modes:

function setDirection(dir: 'north' | 'south' | 'east' | 'west') {
  // dir can ONLY be one of these four strings
}

setDirection('north');   // ✓ Works
setDirection('up');      // ✗ Error: 'up' not assignable

Think of string literal types like a restaurant menu: you can only order what's listed. TypeScript enforces this at compile time, preventing typos and invalid values.

Syntax Variations

You can use single or double quotes:

type Status1 = 'active';
type Status2 = "inactive";

Both work identically — choose what matches your codebase style.

Key Takeaway: String literal types let you constrain a value to an exact string like 'success' or 'error', giving you compile-time guarantees that only valid strings are used.