I'm trying to map a tuple to a new one, which includes all tuple elements at each indicines before its position (SliceStartQuantity
is an external dependecy):
type mappedTuple = mapTuple<[10, 20, 30, 40]> // Expect: [[], [10], [10, 20], [10, 20, 30]]
type mapTuple<T extends any[]> = {[key in keyof T]:SliceStartQuantity<T,0,key>}
However mapTuple
gives an understandable error message, because SliceStartQuantity
requires number
at its third argument:
Type '(number |
${number}
) & key' does not satisfy the constraint 'number'. Type '${number}
& key' is not assignable to type 'number'.
My current really nasty workaround is using a prewritten "casting" type:
type castStringToNumber<T> = T extends '0' ? 0 : T extends '1' ? 1 : T extends '2' ? 2 : T extends '3' ? 3 : T extends '4' ? 4 : never ...etc
By wrapping key (type parameter)
with this, everything works as expected:
type mapTuple<T extends any[]> = {[key in keyof T]:SliceStartQuantity<T,0,castStringToNumber<key>>}
// mappedTuple: [[], [10], [10, 20], [10, 20, 30]]
Is there any way to extract numeric keys while mapping over tuples, cleanly?
using Typescipt 4.8.4