Skip to the solution
MediumFrontend9 min read

What is type widening and how do you prevent it?

312 views

The problem

Question presented to candidate: "Why does let method = "GET" have type string but const method = "GET" has type "GET"? What is type widening, where does it bite you, and what are your options for stopping it?"

What a strong answer should cover:

  • Widening is the compiler replacing a literal type ("GET", 3, true) with its general type (string, number, boolean) when the value lands in a mutable place
  • Where it happens: let and var, object properties, array elements, inferred function return types, and copying a const into a let
  • const with a literal initializer keeps the literal; a literal written with an explicit literal annotation is "non-widening" and survives a copy into a let
  • The classic symptom: send(request.method) fails with "Argument of type 'string' is not assignable to parameter of type 'Method'"
  • The fixes and their trade-offs: annotate the slot, as const (deep, readonly), as const on one property, satisfies, a literal return type, a primitive constraint such as T extends string or a const type parameter
  • Widening is compile-time only; the run-time value is the same string either way

Code / implementation expected: Yes β€” an object literal passed to a function that accepts a literal union, the error, then two or three different fixes.

  • widening
  • 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

9 min read Β· 9 sections

Run the code

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

TypeScriptWhere widening happens and the error it causes
TypeScriptSix ways to keep the literal, and auto-typed variables

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 53 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

Can generics have default types?

Continue