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:
letandvar, object properties, array elements, inferred function return types, and copying aconstinto alet constwith a literal initializer keeps the literal; a literal written with an explicit literal annotation is "non-widening" and survives a copy into alet- 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 conston one property,satisfies, a literal return type, a primitive constraint such asT extends stringor aconsttype 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.