TypeScript · Lesson 41 of 120
as const
The tightest types.
Normally TypeScript widens values. A list of sizes becomes a list of any strings. Adding as const keeps the exact values, and makes everything readonly.

- Values widen
- as const
- Exact and readonly
Types from a list
Sizes is a readonly list of exactly these three strings. We take the type of its items, which becomes the union of the three. Run it. A valid size passes, and the list prints.
app.tstypescript
const SIZES = ["S", "M", "L"] as const;
type Size = (typeof SIZES)[number]; // "S" | "M" | "L"
function check(size: Size) {
return `Size ${size} is in stock`;
}
console.log(check("M"));
console.log(SIZES);Output
Size M is in stock [ 'S', 'M', 'L' ]
Why it's handy
One list gives you both a value to loop over, and a union type. Add a size in one place, and the type updates. As const also works on objects, making every property readonly.
| key | value |
|---|---|
| One list | value and type |
| Add once | type updates |
| Objects | deeply readonly |
| Replaces | many enums |
Summary
As const keeps exact values, so one list can be both a value and a type. Next, type assertions.
Key takeaways- as const
- typeof X[number]
- One source
Next up: Type Assertions — as, carefully