Sub topic 3
Why `let` and `const` Infer Different Types
Assume you know basic TypeScript types, function annotations, object literals, and JavaScript switch statements. This chapter explains how TypeScript infers types for variables whose values look like specific literals.
A literal type is a type containing exactly one value. For example, "dark" is a string literal type, 42 is a numeric literal type, and true is a boolean literal type.
let theme = "dark";
const mode = "dark";
function setMode(value: "dark" | "light"): void {
console.log(value);
}
setMode(mode); // OK
setMode(theme); // Error: string is not assignable to "dark" | "light"Although both variables start with the value "dark", TypeScript gives them different inferred types:
| Declaration | Inferred type | Can the variable change? |
|---|---|---|
| `let theme = "dark"` | `string` | Yes |
| `const mode = "dark"` | `"dark"` | No |
Why `let` widens a literal
A let variable can receive another value later:
let direction = "up";
direction = "down"; // AllowedTo make this assignment valid, TypeScript infers direction as string, rather than the narrower type "up". This behavior is called type widening. Widening changes a specific literal type into a more general type that can represent future assignments.
The same idea applies to numbers and booleans:
let count = 0; // number
let enabled = true; // boolean
count = 1;
enabled = false;You can prevent widening with an explicit annotation:
let direction: "up" | "down" = "up";
direction = "down"; // OK
direction = "side"; // ErrorThis variable remains mutable, but its possible values are restricted to the declared union.
Why `const` keeps a literal
A const variable cannot be reassigned. TypeScript can therefore preserve the exact value as its type:
const direction = "up"; // type: "up"
direction = "down"; // Error: cannot assign to a constantThis makes const useful when a value represents a fixed option. It also allows the compiler to narrow values more precisely when passing them to functions or checking them in conditions.
However, const only prevents reassignment of the variable. It does not automatically make an object or array immutable.
const settings = { mode: "dark" };
settings.mode = "light"; // Allowed
settings = { mode: "light" }; // ErrorThe property settings.mode is inferred as string, because the property can change.
Keeping literal properties with `as const`
An as const assertion tells TypeScript to preserve literal values deeply and mark object properties and array elements as readonly.
const settings = {
mode: "dark",
retries: 3,
logging: true,
} as const;
settings.mode; // type: "dark"
settings.retries; // type: 3
settings.logging; // type: true
settings.mode = "light"; // Error: readonly propertyUse as const when a value is intended to describe a fixed configuration or a set of named options.
const Directions = {
Up: "up",
Down: "down",
Left: "left",
Right: "right",
} as const;
type Direction = (typeof Directions)[keyof typeof Directions];
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move(Directions.Up); // OK
move("left"); // OK
move("diagonal"); // ErrorThe expression typeof Directions obtains the object’s type. keyof typeof Directions produces the key union "Up" | "Down" | "Left" | "Right". Indexing that type with its keys produces the value union "up" | "down" | "left" | "right".
A diagram of widening
Common errors
- Assuming
constmakes an object deeply immutable. It only prevents reassignment of the variable. - Adding
as constto every value without considering whether mutation is required. - Expecting a widened
stringvariable to work where a specific literal union is required. - Using a type assertion to hide an invalid value instead of checking the value at its boundary.
Exercise
What are the inferred types of let level = 1, const status = "ready", and const flags = { debug: false } as const?
Show answer
They are number, the literal type "ready", and an object whose debug property has the literal type false and is readonly.