Question presented to candidate:
"What does as const do in TypeScript? Show me what type you get with and without it, and tell me where you would actually use it."
What a strong answer should cover:
as constis a const assertion: it stops literal widening, makes every propertyreadonlyand turns array literals into readonly tuples, recursively through the literal- The before/after types:
{ method: string }vs{ readonly method: "GET" },string[]vsreadonly ["a", "b"] - Why it matters: values then fit literal-union parameters, and you can derive types from data with
(typeof ROLES)[number]or(typeof Obj)[keyof typeof Obj], an enum alternative - Returning tuples from functions (
return [value, setValue] as const) - Limits: it is compile-time only (nothing is frozen), it only applies to literals (TS1355 otherwise), and it is not a type check
- Related tools:
as const satisfies Tto check a shape while keeping literals (TypeScript 4.9), andconsttype parameters (TypeScript 5.0) to get the same inference at a call site
Code / implementation expected: Yes β a config or list with as const, plus a union type derived from it.