#Why must a helper generic type be used to map a tuple?

6 messages · Page 1 of 1 (latest)

scarlet basinBOT
#
spaethnl#0

Preview:```ts
const x = [
{value: 1},
{value: "str"},
{value: true},
] as const
type X = typeof x

type Y_Expected = readonly [1, "str", true]
type Y_Broken = {
readonly [k in keyof X]: X[k]["value"]
}

type Y_Helper<T extends readonly any[]> = {
readonly [k in keyof T]: T[k]["value"]
}
...```

twin basalt
#

it works there because of the readonly any[], your helper there also doesn't work with the proper unknown[]
i'm not sure why the original doesn't work, but a proper helper type would use T extends readonly { value: unknown }[]

#

i suspect that there's no constraint on X, given it's concrete, so ts doesn't recognize that all values have a value property

#

also possibly that K in keyof T as a homomorphic map over tuples only works if T is generic, since this yields the right result for the elements but not as a tuple:

scarlet basinBOT
#
that_guy977#0

Preview:```ts
const x = [
{value: 1},
{value: "str"},
{value: true},
] as const
type X = typeof x

type Y_Expected = readonly [1, "str", true]
type Y_Direct = {
readonly [I in keyof X]: X[I] extends {
value: infer V
}
? V
: never
}
// ^?

type Y_Helper<T extends readonly {value: unknown}[]> =
{readonly [k in keyof T]: T[k]["value"]}
...```

violet barn