Sub topic 15
Preserving literals with as const
This chapter assumes you know basic TypeScript annotations, the difference between const and let, and how to run tsc or use a TypeScript-aware editor. It also assumes you have read the earlier sections on literal widening and union types.
By default, TypeScript widens literal values to their general type when it infers types for mutable locations. The as const assertion tells the compiler to keep the exact literal values and to mark the result as readonly. You use it when you want the precise values to flow into later type checks.
Why widening loses information
Consider a configuration object:
const config = { port: 8080, mode: "dev" };
// config.port is inferred as number
// config.mode is inferred as stringThe compiler infers number and string because object properties are mutable. A later assignment like config.mode = "prod" must still be valid, so the compiler widens the type. That widening hides the fact that mode only ever holds "dev" in your code.
Applying as const
Adding as const keeps the literal types and makes every property readonly:
const frozen = { port: 8080, mode: "dev" } as const;
// frozen.port has the type 8080
// frozen.mode has the type "dev"
// frozen.port = 9000; // Error: Cannot assign to 'port' because it is a read-only property.Arrays work the same way. Without as const, an array literal infers a widened array type. With as const, it becomes a readonly tuple:
const directions = ["north", "south"] as const;
// type: readonly ["north", "south"]
type Direction = (typeof directions)[number];
// Direction is "north" | "south"The typeof and indexed access combination in the last example derives a union type from a runtime value, so you do not need to repeat the strings.
> Note on scope: as const applies only to the literal expression it is attached to. It does not change the type of a variable declared elsewhere.
Combining as const with validation
as const alone does not check that data matches a shape you expect. The satisfies operator, covered in the next chapter, adds that check while keeping the literal types.
Use as const when you want exact values in your types. Use an explicit annotation when you want a named type that others can import and reuse.
Exercise
Given const sizes = ["small", "medium", "large"] as const;, what type does (typeof sizes)[number] produce, and why does a plain const sizes = ["small", "medium", "large"]; produce a different result?
Show answer
It produces the union "small" | "medium" | "large". Without as const, the array is inferred as string[], so indexing it gives plain string.