Sub topic 1
Why literal types widen
Prerequisites
Assume you know basic TypeScript types, let and const, union types, and type queries such as typeof and keyof.
Why literal types widen
A literal type describes one exact value, such as "left" or 3. TypeScript widens a literal when a value might later change. A mutable variable therefore receives a broader type:
let direction = "left"; // string
direction = "right"; // allowed
const label = "left"; // "left"The const variable cannot be reassigned, so TypeScript can safely preserve "left". However, const does not make every part of an object immutable:
const config = { mode: "dark", retries: 3 };
// { mode: string; retries: number }
config.mode = "light"; // allowedThe object binding is constant, but its properties are still mutable. TypeScript widens those property types to support later assignments.
What `as const` does
as const is a const assertion. It tells TypeScript to keep literal types and mark object properties or array elements as readonly.
const frozen = { mode: "dark", retries: 3 } as const;
// { readonly mode: "dark"; readonly retries: 3 }
// frozen.mode = "light"; // errorFor an array literal, the result is a readonly tuple. A tuple is an array type with a fixed length and a known type at each position.
const pair = ["id", 1] as const;
// readonly ["id", 1]
const first = pair[0]; // "id"
// pair.push(2); // errorReadonly objects with literal properties
Readonly properties prevent assignment through that type. They are useful for configuration, fixed options, and values from which you derive unions.
const Status = {
Active: "active",
Archived: "archived",
} as const;
type Status = (typeof Status)[keyof typeof Status];
const current: Status = Status.Active;
// current = "deleted"; // errorHere, Status is both a runtime object and a type containing "active" | "archived". One value defines both, so the list of allowed statuses cannot silently drift from the runtime constants.
Exercise
What type does const settings = { retries: 3 } as const have for settings.retries?
Show answer
readonly 3.