I have observed an unexpected interaction in the following scenario. When attempting to iterate using the map
function with the generic options
, I noticed that the item inside is not of the expected type.
const foo = <T extends string[]>(options: T, labels: Record<T[number], string>): string[] => {
return options.map(o => labels[o]);
}
The above situation presents a simplified issue that should, in theory, be completely type safe. Given that labels
is a record indexed by the options' index type, it should be capable of being accessed by it. However, the type inferred for the control variable o
in the map
function is string
.
Could this discrepancy be due to incorrect typing within the map
function or is it actually expected behavior?
The simplest solution I have found so far is to specify the type as (o: T[number]) => ...
, but my main interest lies in understanding why this unexpected behavior occurs and exploring the underlying principles behind it.
Edit: Sample usage
foo(["A", "B"] as ["A", "B"], {
A: "Label A",
B: "Label B",
})