Sub topic 4
const, let, and literal widening
This chapter assumes you can write TypeScript functions and objects, and that you know what a union type such as "on" | "off" means. You should also be comfortable reading errors from tsc.
When you declare a variable without an annotation, TypeScript infers its type from the value. The keyword you use, const or let, changes how precise that inferred type is. A const keeps the exact literal type. A let widens the literal to its primitive type.
Literal types and the declaration keyword
A literal type is a type that holds one exact value, such as "Ada" or 42. Compare these two declarations:
const name = "Ada"; // type: "Ada"
let title = "Ada"; // type: stringThe const binding cannot change, so TypeScript can keep the narrow type "Ada". The let binding can be reassigned to any string, so TypeScript widens the type to string. This widening is what people call literal widening.
Widening inside objects and arrays
Widening also applies to properties of mutable objects. Object properties are always mutable by default, so their literal values widen:
const mode = "dark"; // type: "dark"
let theme = mode; // type: string (widened)
const config = { mode: "dark" };
// config.mode has type string, not "dark"Arrays work the same way. const ids = [1, 2, 3] has type number[], not a tuple of literals.
Annotating to keep a narrow type
When you need a narrow type on a mutable binding, add an annotation:
let status: "open" | "closed" = "open";
status = "closed"; // ok
// status = "paused"; // Error: Type '"paused"' is not assignable to type '"open" | "closed"'.The annotation declares the allowed values, so the compiler can check every assignment.
> Callout placeholder removed here.
Exercise
Exercise
What type does TypeScript infer for label in let label = status; when const status = "ready";?
Show answer
string. The const binding has the literal type "ready", but assigning it to a let binding widens the type to string.