Basic as const Syntax
You'll learn how to use as const to lock values into their exact literal types instead of letting TypeScript widen them to general types.
The Problem Recap
You already know that TypeScript widens literal values to their broader primitive types:
let direction = "north"; // Type: string (widened)
Even with type annotations, you still get the broader type:
let status: string = "active"; // Type: string
Introducing as const
The as const assertion tells TypeScript: "Treat this value as a deeply immutable literal type, no widening allowed."
let direction = "north" as const; // Type: "north"
Now direction has the literal type "north", not string.
Basic Syntax
You write as const immediately after the value:
const count = 42 as const; // Type: 42
const enabled = true as const; // Type: true
const name = "Alice" as const; // Type: "Alice"
Note: With const declarations, you often don't need as const for primitives since const already prevents reassignment. But as const becomes powerful with objects and arrays, which you'll learn about next.
Why This Matters
When you want a function to accept only specific literal values, as const ensures your value stays narrow:
let mode = "dark" as const;
// mode has type "dark", perfect for strict function parameters
Key Takeaway: as const prevents type widening, preserving exact literal types for values that should never change.