Sub topic 3
Why let and const infer different types
This chapter assumes you know basic TypeScript types, can annotate functions, and have seen union types such as string | number. It builds on the previous chapters on literal types and unions of literals. Here you will learn why the same string literal gets the type "up" in one declaration and string in another, and how to fix the errors that follow.
The same value, two different types
Compare these two declarations:
let a = "up"; // type: string
const b = "up"; // type: "up"Both are initialized with the same value. The compiler gives them different types because of what each declaration allows later:
- A
letvariable can be reassigned. Ifahad the type"up", the linea = "down"would be an error, and almost nobody wants that from a plainlet. TypeScript guesses that you meant "some string" and infersstring. - A
constvariable can never be reassigned. Its value is always"up", so the most precise type,"up", is also the safe one.
This guess is called type widening. TypeScript starts from the literal type of the initializer and widens it to the base type (string, number, boolean, and so on) when the location is mutable. The base type is what lets later assignments work without friction.
Where widening happens
The rule is about the location, not the value. Any place that can be changed later widens the literal. Any place that cannot be changed keeps it.
| Declaration | Inferred type | Reason |
|---|---|---|
| `let s = "up"` | `string` | `let` can be reassigned |
| `var s = "up"` | `string` | `var` can be reassigned |
| `const s = "up"` | `"up"` | `const` cannot be reassigned |
| `let n = 42` | `number` | mutable |
| `const n = 42` | `42` | immutable |
| `let ok = true` | `boolean` | mutable |
| `const ok = true` | `true` | immutable |
| `const o = { mode: "dark" }` | `{ mode: string }` | properties are mutable |
| `const xs = ["up", "down"]` | `string[]` | array elements are mutable |
The last two rows surprise many people. const fixes the binding, meaning the variable name always refers to the same object. It does not freeze the contents of the object. You can still write o.mode = "light", so TypeScript types mode as string.
const o = { mode: "dark" };
o.mode = "light"; // allowed: mode is string
const xs = ["up", "down"];
xs.push("left"); // allowed: xs is string[]If mode had been inferred as "dark", the assignment on the second line would fail even though JavaScript allows it. Widening keeps TypeScript's inference aligned with what the runtime permits.
Fresh literals and the widening literal type
There is a detail behind the const case that affects real code. When you write const b = "up", the type of b is not an ordinary "up". It is a widening literal type: it reads as "up", but it remembers that it came from an unannotated initializer. If you copy it into a mutable location, it widens at that point.
const b = "up"; // widening literal type "up"
let c = b; // string: widened when copied into a let
const d: "up" = "up"; // annotation makes this a non-widening "up"
let e = d; // "up": the annotation prevents wideningSo c is string, but e is "up". The annotation tells TypeScript that you chose this exact type on purpose, so it does not second-guess you.
You will not need this distinction often. It explains why a let copied from a const still behaves like a let and gets a base type.
The common error: a widened property meets a union
The most frequent trouble comes from combining widening with the unions you learned earlier. Suppose a function accepts only a fixed set of strings:
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
const options = { direction: "up" };
move(options.direction);
// Error: Argument of type 'string' is not assignable to parameter of type 'Direction'.The literal "up" is a valid Direction. But options.direction is a mutable property, so TypeScript widened it to string when it inferred the type of options. By the time you pass it to move, the compiler no longer knows it was ever "up". A string could be "diagonal", so the call is rejected.
Calling move("up") directly works because a literal written at the call site is checked against the parameter type, and "up" matches. The error only appears once the literal has been stored somewhere mutable first.
Three ways to fix it
Pick the one that matches what you want the code to mean.
- Annotate the variable, so the property is typed as
Directionfrom the start. - Use
as const, so the whole object keeps its literal types and becomes read-only. - Assert the single value at the point of use.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
// 1. Annotation: the object's property is a Direction.
const annotated: { direction: Direction } = { direction: "up" };
move(annotated.direction); // OK
// 2. as const: every property keeps its literal type and is readonly.
const frozen = { direction: "up" } as const;
move(frozen.direction); // OK
// 3. Assertion on the value: only this property is narrowed.
const asserted = { direction: "up" as Direction };
move(asserted.direction); // OKOption 1 is usually the best choice. It documents intent, and it lets the compiler reject a wrong initial value such as "diagonal" at the declaration instead of at a later call. Option 2 is covered in detail in the next chapter. Option 3 should be used with care: "up" as Direction works, but so does "diagonal" as Direction when you write it by mistake, because an assertion from a string literal to a union of literals is accepted as long as the types overlap in a compatible way. Assertions bypass part of the check you were trying to get.
Annotated `let` and narrowing on assignment
An annotation on a let gives it the declared type you wrote, not the widened one:
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
let current: Direction = "up";
move(current); // OK
current = "left"; // OK: still a Direction
current = "diagonal";
// Error: Type '"diagonal"' is not assignable to type 'Direction'.The declared type of current is Direction, so it can hold any of the four values. Right after the initial assignment, though, the compiler narrows it by control flow to "up" for the next statements. If you write if (current === "down") immediately after let current: Direction = "up";, TypeScript reports that the comparison has no overlap, because it knows the value is "up" at that point. The narrowing resets whenever the variable can change, for example inside a callback or after a function call that might reassign it. This is why code that works in a straight line can produce a surprising error and then stop doing so after a loop or a closure.
Widening affects comparisons too
Widening is not only about passing arguments. It also decides which comparisons are allowed:
let a = "up";
if (a === "down") {
// OK: a is string, so any string literal is comparable
}
const b = "up";
if (b === "down") {
// Error: This comparison appears to be unintentional because the types
// '"up"' and '"down"' have no overlap.
}The second error is the compiler correctly noticing that b can never equal "down". This check is helpful when it catches a typo and annoying when you wrote a placeholder. It is another sign that const literals carry real information.
Function return types widen as well
A function that returns a literal does not return a literal type unless you say so:
function pick() {
return "up"; // inferred return type: string
}
function pickTyped(): "up" {
return "up"; // return type: "up"
}The return value of pick could be stored in a let, so TypeScript widens it. The annotation on pickTyped states the exact type you want. When a function should return one of a fixed set of values, annotate the return type with the union rather than relying on inference.
How TypeScript decides
The diagram summarizes the decision for a literal initializer.
For object properties and array elements, the right-hand branch applies even under const, because the property or element is itself a mutable location.
Edge cases to remember
booleanis already a union. The typebooleanis the same astrue | false. Solet ok = truewidens toboolean, andconst ok = truekeepstrue.- Only primitives get literal types.
const list = []orconst obj = {}never produces a literal type for the whole value. The widening rules apply to the primitives inside them. constdoes not freeze at runtime either. OnlyObject.freezedoes that, and it is shallow. TypeScript'sas constis a compile-time device that addsreadonlyto the type. It does not callObject.freeze.- Contextual typing can prevent widening. When the destination type is known, as in a typed parameter, a typed property, or an annotated variable, the literal is checked against that type directly and never widens. That is why
move("up")works.
Summary
TypeScript infers a literal type only when nothing can change it later. A const primitive keeps its literal type, and a let, a property, or an array element widens to string, number, or boolean. When widening breaks a call that expects a union of literals, add an annotation, use as const, or assert the single value, in that order of preference.
Exercise
Given type Mode = "light" | "dark"; and function setMode(m: Mode): void {}, explain why const settings = { mode: "dark" }; setMode(settings.mode); fails, and rewrite the declaration of settings so the call compiles without using as.
Show answer
settings is a const object, but its property mode is mutable, so TypeScript widens "dark" to string. A string is not assignable to Mode, so the call fails. Annotate the object: const settings: { mode: Mode } = { mode: "dark" };. The property is now typed as Mode, and setMode(settings.mode) compiles. Writing as const on the object would also work.
Exercise
What are the types of x, y, and z in const a = "go"; let x = a; const y = a; let z: "go" = a;?
Show answer
x is string, because a has a widening literal type and copying it into a let widens it. y is "go", because a const copy keeps the literal type. z is "go", because the annotation sets the declared type explicitly.