Sub topic 1
Why Literal Types Widen
Prerequisites
This chapter assumes that you know basic TypeScript types such as string, number, arrays, and object types. You should also know the difference between let and const, and understand union types and literal types such as "left" | "right".
Literal types describe exact values
A literal type is a type that represents one exact value. For example, "left" is a string value, but it can also be the literal type "left".
let direction: "left" = "left";
const count: 3 = 3;The type "left" permits only the string "left". The type 3 permits only the number 3.
Literal types are useful when a value must come from a small, known set:
type Alignment = "left" | "center" | "right";
function align(text: string, alignment: Alignment) {
console.log(`${alignment}: ${text}`);
}
align("Hello", "center"); // OK
// align("Hello", "diagonal"); // ErrorTypeScript often infers literal types from literal expressions. However, it does not always keep them. In many situations, it widens a literal type to a more general type.
Why TypeScript widens values
Widening means replacing a specific type with a less specific type. TypeScript widens a value when it expects that the value may change later.
let a = "left";
// string
const b = "left";
// "left"The let variable a can receive another string:
let a = "left";
a = "right"; // OKIf TypeScript inferred a as "left", this assignment would be invalid. Therefore, TypeScript infers a as string.
The const variable b cannot be assigned a new value. TypeScript can safely preserve its exact type:
const b = "left";
// "left"
// b = "right"; // Error: cannot assign to a constantThe same rule applies to numeric, Boolean, and bigint literals.
| Declaration | Initial value | Inferred type |
|---|---|---|
| `let count = 3` | `3` | `number` |
| `const count = 3` | `3` | `3` |
| `let enabled = true` | `true` | `boolean` |
| `const enabled = true` | `true` | `true` |
This behavior is about the inferred type, not about whether the runtime value currently changes.
`const` does not make an object immutable
A common mistake is to assume that const preserves every literal inside an object. It only prevents reassignment of the variable itself.
const config = {
mode: "dark",
retries: 3,
};
// Inferred type:
// {
// mode: string;
// retries: number;
// }
config.mode = "light"; // OK
config.retries = 5; // OKThe object binding cannot point to a different object:
const config = { mode: "dark" };
// config = { mode: "light" }; // ErrorHowever, the properties are still mutable. Because config.mode can change, TypeScript widens "dark" to string. It widens 3 to number for the same reason.
The important distinction is:
constprotects the binding.- It does not automatically protect the contents of an object or array.
- Mutable properties need general types that allow later assignments.
Arrays widen for the same reason
An array created without a type annotation is usually inferred as a mutable array, not as a fixed tuple.
const pair = ["id", 1];
// Inferred type:
// (string | number)[]This array can change its length and replace its elements:
pair.push("name"); // OK
pair[0] = "name"; // OK
pair[1] = 2; // OKSince the array is mutable, TypeScript cannot safely infer the exact values or positions. The first element is not permanently "id", and the second element is not permanently 1.
The result is a union array. (string | number)[] means that every element may be either a string or a number.
Context can prevent widening
An expected type can give a literal a narrower meaning. This is called contextual typing. The surrounding type provides context for the expression.
type Request = {
method: "GET" | "POST";
};
const request: Request = {
method: "GET",
};Here, method is checked against "GET" | "POST", so "GET" is accepted as one of the allowed literal types.
Without the annotation, the property would usually widen:
const request = {
method: "GET",
};
// method is inferred as stringThat difference can matter when passing values to functions:
function send(method: "GET" | "POST") {
console.log(method);
}
const first = { method: "GET" };
// send(first.method); // Error: string is not assignable to "GET" | "POST"
const second: { method: "GET" | "POST" } = { method: "GET" };
send(second.method); // OKA model for predicting widening
When you see a literal expression, ask whether the value is in a mutable position.
A variable declared with let is mutable, so its string literal usually widens. A primitive variable declared with const is not reassigned, so its literal type can remain narrow. An object declared with const still has mutable properties, so its property values usually widen. A type annotation can provide an expected union type and control the result.
When widening becomes a problem
Widening is usually helpful. It lets ordinary variables change without requiring annotations everywhere. It becomes a problem when you want a runtime value to define a precise set of allowed values.
const roles = ["admin", "editor", "viewer"];
function openPanel(role: "admin" | "editor" | "viewer") {
console.log(`Opening panel for ${role}`);
}
// openPanel(roles[0]); // Error: roles[0] is stringThe array contains valid role names, but its inferred type is string[]. TypeScript has lost the relationship between the actual values and the desired union type.
The next step is to use a const assertion. as const tells TypeScript to preserve literal types and treat the resulting object or array as readonly.
Exercise
What types does TypeScript infer for let x = "open" and const y = "open", and why are they different?
Show answer
x is inferred as string because a let variable can later hold another string. y is inferred as the literal type "open" because a primitive const binding cannot be reassigned.