Course contentsShow
← TypeScript
Lesson 163 of 1,7964. Type InferenceFree lesson

Literals and Widening: When Inference Hurts

How inference widens literals to primitives by default and when annotations preserve the narrow literal type you need.

Literals and Widening: When Inference Hurts

You'll learn when TypeScript's helpful inference becomes too broad and how to preserve exact literal types.

The Widening Problem

TypeScript wants to be helpful. When you write let status = "success", it infers the type as string, not the literal "success". This is called widening—TypeScript assumes you might reassign the variable later, so it gives you flexibility.

But sometimes this backfires. Imagine a function that only accepts "success" or "error". If you try passing your status variable, TypeScript complains: you have a string, but the function wants a specific literal.

How const Prevents Widening

The const keyword signals you won't reassign, so TypeScript keeps the narrow literal type:

let status = "success";  // Type: string
const statusFixed = "success";  // Type: "success"

When You Need Annotations

Sometimes you can't use const (like with object properties or function parameters). That's when you explicitly annotate to preserve the literal:

let status: "success" | "error" = "success";  // Type: "success" | "error"

Now status can only be those two exact strings, not any string.

The Inference vs Control Balance

Widening happens because TypeScript balances convenience with safety. Most of the time, widening to string is what you want. But when working with APIs that expect exact values, you need to take control with const or explicit annotations.

Key Takeaway: TypeScript widens let declarations from literals to primitives for flexibility; use const for automatic narrowing or explicit annotations when you need precise literal types.