Sub topic 7
Literal Types and Widening
Assume you know basic TypeScript annotations, interfaces, unions, and functions. This chapter explains why a value that appears to be "fast" can sometimes have type string, and why that difference affects assignability.
Literal types are exact values
A literal type represents one exact value. For example, "fast" is a string literal type, while 42 is a numeric literal type.
A union of literal types describes a fixed set of allowed values:
type Mode = "fast" | "slow";
function start(mode: Mode): void {
console.log(`Starting in ${mode} mode`);
}
const fixed = "fast"; // type: "fast"
start(fixed); // OK
const config = { mode: "fast" };
// config.mode has type string
// @ts-expect-error string is wider than Mode
start(config.mode);The const variable fixed cannot be reassigned, so TypeScript preserves its specific literal type. The object property config.mode is mutable. It could later become another string, so TypeScript widens its type to string.
Widening and assignment
Widening changes a specific literal type into a broader type when the value is stored in a location that may change.
let mode = "fast"; // string
const fixedMode = "fast"; // "fast"
let selected: Mode = "fast"; // Mode
const selectedFixed: Mode = "fast"; // Mode
const config = { mode: "fast" };
const safeConfig = { mode: "fast" } as const;
console.log(mode, fixedMode, selected, selectedFixed, config, safeConfig);An explicit annotation is often the clearest solution. as const applies a const assertion: it preserves literal types and makes object properties and array elements readonly.
Contextual typing can also prevent widening. When TypeScript already knows the expected type, it checks the literal against that type:
type Config = {
mode: "fast" | "slow";
};
const config: Config = {
mode: "fast"
};
config.mode = "slow"; // OKHere, the annotation gives config.mode the union type rather than the general string type.
A practical decision rule
Use a literal union when the program should accept only known values. Add an annotation when an object must satisfy that union and remain mutable. Use as const when the entire value should retain exact literals and become readonly.
Exercise
Why does const settings = { mode: "fast" } usually give settings.mode the type string, while const mode = "fast" gives mode the type "fast"?
Show answer
A standalone const variable cannot be reassigned, but an object property remains mutable. TypeScript therefore preserves the standalone literal and widens the mutable property.