Sub topic 4
const, let, and literal widening
This chapter explains why TypeScript infers "Ada" for a const and string for a let that holds the same value. It also covers the places where this surprises people, such as object properties and function arguments. It assumes you can read basic TypeScript annotations and know that TypeScript infers types from initial values. Those are covered in the earlier chapters on primitives and inference.
Literal types
A literal type is a type that contains exactly one value. The value "Ada" has the literal type "Ada", 42 has the literal type 42, and true has the literal type true. A literal type is narrower than its primitive: every "Ada" is a string, but not every string is "Ada".
You can write literal types yourself:
let exact: "Ada" = "Ada";
// exact = "Grace"; // Error: Type '"Grace"' is not assignable to type '"Ada"'.
type Answer = 42;
const answer: Answer = 42;
console.log(exact, answer);Most of the time you don't write them. The compiler chooses between a literal type and its primitive when it infers a type, and that choice is called widening.
What widening is
Widening is the compiler replacing a literal type with its general primitive type when it infers the type of a variable that can change. The compiler asks one question: can this location hold a different value later?
- A
constbinding cannot be reassigned, so the compiler keeps the exact literal type. - A
letorvarbinding can be reassigned, so the compiler widens to the primitive.
const language = "TypeScript"; // type: "TypeScript"
let editor = "TypeScript"; // type: string
const retries = 3; // type: 3
let attempts = 3; // type: number
const enabled = true; // type: true
let visible = true; // type: boolean
editor = "Another editor"; // ok, editor is a string
// language = "JavaScript"; // Error: Cannot assign to 'language' because it is a constant.
console.log(language, editor, retries, attempts, enabled, visible);If the compiler gave editor the type "TypeScript", the second assignment would be an error, and that would make let nearly useless. Widening keeps let usable without annotations.
The rule covers every primitive that has literal forms.
| Declaration | Inferred type |
|---|---|
| `const a = "x"` | `"x"` |
| `let a = "x"` | `string` |
| `const n = 7` | `7` |
| `let n = 7` | `number` |
| `const b = false` | `false` |
| `let b = false` | `boolean` |
| `const big = 10n` | `10n` |
| `let big = 10n` | `bigint` |
| `const s = Symbol("id")` | `unique symbol` (shown as `typeof s`) |
| `let s = Symbol("id")` | `symbol` |
The let and const rows for symbol differ in the same way as the others. A const symbol gets its own unique type, which is the symbol equivalent of a literal type.
Widening in a declaration you didn't write
Widening also happens at places that are not obviously declarations.
A const with a literal type loses it as soon as the value is copied into a mutable location. The literal type that a const gets is called a widening literal type, and it widens whenever it flows into a let:
const base = "left"; // type: "left"
let copy = base; // type: string, the literal widened
const fixed: "left" = "left"; // explicit annotation: non-widening
let copy2 = fixed; // type: "left"
copy2 = "left"; // ok
// copy2 = "right"; // Error: Type '"right"' is not assignable to type '"left"'.
console.log(copy, copy2);An inferred literal widens when copied, while a literal that comes from an annotation stays as it is.
Function return types widen too. A function that returns a literal gets the primitive as its return type:
function version() {
return "1.0"; // inferred return type: string
}
const v = version(); // v is string, not "1.0"
console.log(v);Loop counters follow the let rule: in for (let i = 0; i < 3; i++), i is a number, which is what makes i++ legal.
Where widening causes errors
Widening is invisible until a value flows into something that accepts only specific literals. Here is the most common case, a function with a literal-union parameter:
type Direction = "left" | "right";
function move(direction: Direction): string {
return `moving ${direction}`;
}
const a = "left";
console.log(move(a)); // ok: a is "left"
let b = "left";
// move(b); // Error: Argument of type 'string' is not
// // assignable to parameter of type 'Direction'.b is a string, and a string could be "up", so the call is rejected. There are two fixes. You can change let to const if the variable never changes. If it does change, annotate it:
type Direction = "left" | "right";
function move(direction: Direction): string {
return `moving ${direction}`;
}
let heading: Direction = "left";
console.log(move(heading));
heading = "right";
console.log(move(heading));Now heading can hold either value, and the compiler accepts every call. Literal unions are the subject of a later chapter. For now, the point is that the annotation tells the compiler how much to widen.
Object properties widen even inside const
The const rule applies to the binding. It does not apply to the properties of an object. Properties can be reassigned, so each one is widened:
type Method = "GET" | "POST";
function send(method: Method, url: string): string {
return `${method} ${url}`;
}
const request = { method: "GET", url: "/users" };
// request.method has type string, not "GET"
// send(request.method, request.url);
// Error: Argument of type 'string' is not assignable to parameter of type 'Method'.const request cannot be rebound, but request.method = "DELETE" is legal JavaScript, so the compiler infers string. Arrays behave the same way: const names = ["Ada"] has type string[].
Three fixes are common:
- Annotate the object:
const request: { method: Method; url: string } = { ... }. - Annotate only the property by writing the literal where the context expects it, for example
send("GET", "/users"). - Use
as const, which freezes the literal types in place. A later chapter covers it.
type Method = "GET" | "POST";
function send(method: Method, url: string): string {
return `${method} ${url}`;
}
const request: { method: Method; url: string } = {
method: "GET",
url: "/users",
};
console.log(send(request.method, request.url));Annotations override inference
An explicit annotation always wins, including on a const:
const inferred = "Ada"; // type: "Ada"
const annotated: string = "Ada"; // type: string
type A = typeof inferred; // "Ada"
type B = typeof annotated; // stringChoosing between inference and annotation
- Let a
constinfer its literal when the value is a fixed constant. - Annotate a
letwith a union when the variable will hold several specific values over time. - Annotate a
letwith the primitive only when you want the broad type. In that case the inferred type is already that, so the annotation is redundant. - When an object feeds a function that wants literals, annotate the object, or use
as constorsatisfies(covered in later chapters).
Common mistakes
- Assuming
conston an object makes its fields literal. Fields widen. - Writing
letout of habit for values that never change, then hitting an argument error. Preferconstby default. - Expecting
let x = "a"to be usable where"a"is required. - Annotating a
constwithstringand then losing its literal type.
Exercise
Given the code below, state the type of each of the four variables (p, q, r, s). Then say which of the two calls to paint compiles, and give one change that fixes the other.
type Color = "red" | "blue";
function paint(c: Color): void {}
const p = "red";
let q = "red";
const r = { color: "red" };
const s: string = "red";
paint(p);
paint(q);
Show answer
p is "red" (a const keeps the literal). q is string (a let widens). r is { color: string } (properties widen even inside a const). s is string (the annotation overrides inference). paint(p) compiles because "red" is assignable to Color. paint(q) fails because string is not assignable to Color. Fix it by changing let q to const q, or by annotating it as let q: Color = "red".