Skip to the solution
MediumFrontend8 min read

What are const type parameters (<const T>) and why are they better than as const?

479 views

The problem

Question presented to candidate: "TypeScript 5.0 added const type parameters, as in function f<const T>(x: T). What do they do, and why would a library author use them instead of asking callers to write as const?"

What a strong answer should cover:

  • <const T> makes tsc infer T as if the argument literal had been written as const: literal types, readonly properties and readonly tuples, all the way down
  • The benefit: the precision is decided once by the function author, not remembered by every caller; the call site stays clean
  • Limits: it only affects literals written in the call (a variable that was already widened stays widened), an explicit type argument turns it off, and the result is readonly
  • Constraints matter: use readonly unknown[]-style array constraints; with a mutable array constraint, 5.0 fell back to the constraint, and 5.3 relaxed that (on 5.4.5 the result is a mutable tuple)
  • Allowed on type parameters of functions, methods and classes, not interfaces or type aliases (error TS1277); it is erased at run time and freezes nothing

Code / implementation expected: Yes β€” a small defineOptions or defineRoutes helper written with and without const, with Equal checks of the inferred type.

  • generics
  • const-type-parameters

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

8 min read Β· 9 sections

Run the code

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

TypeScriptPlain generic vs as const vs a const type parameter
TypeScriptThe limits: variables, explicit type arguments, constraints and classes

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 46 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 nextMedium

How do you safely work with JSON of unknown shape?

Continue