Skip to the solution
MediumFrontend10 min read

What does as const do?

63 views

The problem

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 const is a const assertion: it stops literal widening, makes every property readonly and turns array literals into readonly tuples, recursively through the literal
  • The before/after types: { method: string } vs { readonly method: "GET" }, string[] vs readonly ["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 T to check a shape while keeping literals (TypeScript 4.9), and const type 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.

  • as-const
  • literal-types

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptWhat as const changes, proved with type checks
TypeScriptDeriving unions, enum-like objects and as const satisfies

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 65 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

What is key remapping in mapped types?

Continue