Sub topic 1
Why literal types widen
TypeScript gives const x = "left" the type "left", but let x = "left" the type string. This chapter explains that difference. It covers where widening happens, why the compiler does it, and the errors it causes. The chapters that follow use as const to control widening, so this one explains the problem it solves.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript types:
string,number,boolean, arrays, and object types. - The difference between
letandconstin JavaScript. - Union types and literal types such as
"a" | "b". - How
typeofandkeyofwork in type positions. You only need them from the next chapter on, and this chapter barely touches them.
The examples use strict mode and TypeScript 4.9 or later. Widening behaves the same way in older versions back to 2.1, where it was introduced.
Literal types and their widened types
A literal type describes exactly one value. The type "left" accepts the string "left" and nothing else. The type 42 accepts only the number 42. The type string accepts every string, so it describes a set of values and not one value.
Every literal expression in your code starts out with a literal type. Writing "left" gives you a value of type "left". Each literal type has a wider type that contains it:
| Literal type | Widened type |
|---|---|
| `"left"` | `string` |
| `42` | `number` |
| `true` or `false` | `boolean` |
When TypeScript has to choose a type for a variable or property, it often replaces the literal type with its widened type. That replacement is called widening.
The next section shows the pattern in code.
Widening in practice
The first example compares let with const, then adds an object literal.
let a = "left"; // string
const b = "left"; // "left"
const config = { mode: "dark", retries: 3 };
// { mode: string; retries: number }Each line follows from one rule. A const variable cannot be reassigned, so its type can safely be the single value it holds. A let variable can be reassigned, so its type has to allow other values of the same kind.
The config object is the surprising case. The variable is const, yet its properties are typed string and number. The const keyword stops you from reassigning config. It does not stop you from changing config.mode:
const config = { mode: "dark", retries: 3 };
config.mode = "light"; // allowed
config.retries = 5; // allowedBecause object properties are mutable by default, TypeScript treats each property like a let variable and widens it.
The rule behind it
TypeScript widens a literal when the value lands in a mutable location and nothing else tells it to keep the literal. The mutable locations you meet most often are:
- A
letorvarvariable declared without a type annotation. - A property in an object literal.
- An element in an array literal.
- A class property without
readonlyor a type annotation.
Arrays follow the same rule as objects:
const sizes = [1, 2, 3]; // number[]
const mixed = ["a", 1]; // (string | number)[]Each element type is widened, so [1, 2, 3] becomes number[]. It does not become (1 | 2 | 3)[], and it does not become a tuple.
Why TypeScript widens
The default is a deliberate choice, and it follows from how people use mutable values. Suppose widening did not exist and let kept the literal type:
let direction = "left";
direction = "right"; // would be an error if direction had the type "left"The type "left" would make this reassignment an error. Almost nobody declares a let variable to hold one value forever. The let keyword itself says "this will change". A type of string matches that intent.
Object properties follow the same logic. Most code that builds an object and later updates it expects the property to hold other strings. Under a literal-preserving rule, this code would fail to compile:
const user = { role: "viewer" };
user.role = "admin"; // fine, because role is stringSo widening makes the common case work. The cost is that you lose precision when you want it. That cost is the subject of the next section.
When widening gets in your way
Widening causes trouble when a function accepts a union of literals and you pass a value that was widened first:
type Direction = "left" | "right";
function move(d: Direction): void {
console.log(`moving ${d}`);
}
move("left"); // OK: the literal is checked directly against Direction
const settings = { dir: "left" };
// move(settings.dir);
// error: Argument of type 'string' is not assignable to parameter of type 'Direction'.
let current = "right";
// move(current);
// error: Argument of type 'string' is not assignable to parameter of type 'Direction'.Both values look correct to a reader, because "left" and "right" are valid directions. But settings.dir was widened to string when the object was created, and current was widened when it was declared. TypeScript checks types, not the value you can see in the source, so it rejects both calls. The call move("left") passes because the literal expression goes straight to the parameter, and no widening happens along the way.
This is the most common widening error in real code. It shows up with configuration objects, route tables, lists of allowed values, and action creators.
Why `const` variables are different
A const declaration without an annotation keeps the literal type because the variable can never hold anything else:
const mode = "dark"; // "dark"There is a subtlety here that explains some confusing behavior. The type TypeScript gives mode is a widening literal type. It is the type "dark" with a hidden mark saying "this literal came from an expression and may still be widened". The mark matters when you copy the variable into a mutable location:
const b = "left";
let c = b; // string: the widening literal type is widened again
const d: "left" = "left";
let e = d; // "left": an annotated literal type is never widenedThe variable b has the type "left", but because that type is still marked as widenable, let c = b widens it to string. The variable d has an explicit annotation. The annotation produces a non-widening literal type, so let e = d keeps "left".
The mark is internal. You never see it in hover text or in error messages, and the compiler does not let you write it. The practical rule is simple: literal types that come from inference can widen later, and literal types that you wrote in an annotation cannot.
The flow chart summarizes the decision the compiler makes for each literal value.
Tools that skip widening
Widening is a default, and several things override it. The overrides matter because they show what the compiler needs in order to keep a literal.
Type annotations
If you write the type yourself, TypeScript uses it:
type Direction = "left" | "right";
let current: Direction = "right"; // type is Direction, not string
const settings: { dir: Direction } = { dir: "left" };
move(current); // OK
move(settings.dir); // OKAnnotations are explicit and stable. The cost is that you repeat the shape of the value. For large nested objects this becomes tedious.
Contextual types
TypeScript also skips widening when the position the value sits in has an expected type that includes literal types. This happens when you pass an object literal directly to a function:
type Direction = "left" | "right";
function setLayout(options: { dir: Direction; gap: number }): void {
console.log(options.dir, options.gap);
}
setLayout({ dir: "left", gap: 8 }); // OKHere the property dir has an expected type of Direction. A literal type is allowed in that position, so "left" stays "left". If you first assign the same object to a variable, the context is gone, and the property widens:
const options = { dir: "left", gap: 8 };
// setLayout(options);
// error: Type 'string' is not assignable to type 'Direction'.The object is identical in both calls, but only the first call gives the compiler a reason to keep the literal. This difference is one of the most common sources of confusion with widening.
Type assertions
You can tell the compiler you know better:
const dir = "left" as Direction;For a single literal this is harmless. For anything bigger it is risky, because an assertion silences the compiler instead of proving anything. Writing { dir: "lft" } as { dir: Direction } does not compile, but wider mistakes can slip through, because assertions only require that the two types sufficiently overlap. Treat assertions as a last resort.
Const assertions
The fourth option is the subject of this tutorial. Adding as const after a literal tells the compiler to keep every literal type and to mark object properties and array elements as readonly:
const frozen = { mode: "dark", retries: 3 } as const;
// { readonly mode: "dark"; readonly retries: 3 }You do not need to write a type, and the compiler does not guess a widened one. The next chapter covers exactly what as const does and how to apply it.
Things that do not widen
A few cases surprise people because they expect widening and do not get it.
- A
constdeclaration keeps its literal type, as shown above. - A parameter or variable with an explicit annotation keeps that annotation exactly.
- Type-level code is not affected. Widening applies to inferred types for values, not to types you write in
typealiases.
Widening also affects only the type, not the value. At runtime, let a = "left" and const b = "left" both hold the same string. TypeScript removes types when it compiles to JavaScript, so none of the behavior in this chapter leaves a trace in the output.
Seeing widened types yourself
You can check what the compiler inferred in three ways:
- Hover over the variable in your editor.
- Run
tsc --noEmitand read the error messages, which print the inferred type. - Ask for the type in a throwaway line, such as
type T = typeof config;, and hover overT.
When a union-of-literals error appears, look at where the value was created. The type was almost always decided at that point, and the line where the error is reported only shows the result.
Common mistakes
- Assuming
constfreezes an object. The keyword fixes the binding. It does not make properties readonly or keep their literal types. - Annotating the wrong place. Writing
let current: string = "right"removes the literal on purpose, and thenmove(current)fails. Annotate with the union type instead. - Fixing the error with
as Directioneverywhere. This works but disables checking. If the object has many properties, prefer an annotation or a const assertion. - Expecting an array of strings to be a union. The type of
["a", "b"]isstring[], not"a" | "b". The next chapters show how to derive a union from such a list.
Summary of the model
Each literal expression starts with a literal type. TypeScript widens it to string, number, or boolean when the value goes into a mutable location, such as a let variable, an object property, or an array element, and nothing tells it to keep the literal. Annotations and contextual types that include literals prevent widening. A const variable keeps a literal type that can still widen if you copy it into a mutable location. Const assertions give you a way to keep literal types without writing the types out.
Exercise
Given const point = { x: 1, y: 2 }; and let label = "origin";, what are the types of point, point.x, and label? Why is point.x not the type 1, even though point is declared with const?
Show answer
point is { x: number; y: number }, point.x is number, and label is string. The const keyword only prevents reassigning the variable point. The properties of an object literal are mutable, so TypeScript widens each literal to number. The let variable label is widened to string because it can be reassigned.
Exercise
This code fails to compile. Why does the second call work when the first does not, and what is the smallest change that makes the first call compile without using as?
type Direction = "left" | "right";
function move(d: Direction): void {}
const options = { dir: "left" };
move(options.dir);
move("left");
Show answer
In options, the property dir is widened to string when the object is created, because nothing tells the compiler to keep the literal. move(options.dir) then passes a string where Direction is expected, which is an error. In move("left") the literal goes directly into a position typed Direction, so it is checked as the literal "left". The smallest fix is to annotate the object: const options: { dir: Direction } = { dir: "left" };. That gives the property the type Direction, so the first call compiles.
Exercise
What is the type of c and of e in the following code, and what explains the difference?
const b = "left";
let c = b;
const d: "left" = "left";
let e = d;
Show answer
c is string and e is "left". The type that TypeScript infers for b is a widening literal type, so copying b into a let widens it again. The type of d comes from an explicit annotation, which produces a non-widening literal type, so e keeps "left".