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

as const on Primitive Values

How as const locks string, number, and boolean values to their exact literal types.

as const on Primitive Values

What you'll learn: How as const locks primitive values to their exact literal types instead of widening to general types.

The Lock-In Mechanism

When you apply as const to a string, number, or boolean value, TypeScript stops widening it to the general primitive type. Instead, it treats the value as its own unique literal type.

Without as const, even const declarations allow TypeScript to widen values in certain contexts (like when stored in objects or passed to functions). The as const assertion tells TypeScript: "This exact value is the type—don't generalize it."

// Without as const - widens to string
const name = "Alice"; // Type: "Alice" (const helps here)
let city = "Paris";   // Type: string (let always widens)

// With as const - locked to literal
const role = "admin" as const;     // Type: "admin"
let status = "active" as const;    // Type: "active"

// Works with numbers too
const maxRetries = 3 as const;     // Type: 3
const pi = 3.14159 as const;       // Type: 3.14159

// And booleans
const isEnabled = true as const;   // Type: true (not boolean)

Why This Matters

This is powerful when you want to enforce exact values in function parameters or union types:

function setTheme(theme: "light" | "dark") {
  // implementation
}

const userTheme = "dark" as const;
setTheme(userTheme); // ✓ Works - type is exactly "dark"

const otherTheme = "dark"; // Type: "dark" (const already narrows)
setTheme(otherTheme); // ✓ Also works with const

let mutableTheme = "dark"; // Type: string
setTheme(mutableTheme); // ✗ Error - string isn't "light" | "dark"

Key Takeaway: as const on primitive values locks them to their exact literal type, preventing widening even when used in contexts where TypeScript might otherwise generalize them to string, number, or boolean.