AI Hints
Home›TypeScript Tutorial›Enums and Assertions
TypeScript · Lesson 41 of 120

as const

The tightest types.

⏱ 2 min read▶ Video at 32:39🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

as const
From the video: as const
  • 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.

keyvalue
One listvalue and type
Add oncetype updates
Objectsdeeply readonly
Replacesmany 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