0

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

themajashurka
  • 171
  • 2
  • 7
  • 1
    what is `SliceStartQuantity` ? – Tobias S. Oct 24 '22 at 08:12
  • a utility function from this library: https://www.npmjs.com/package/typescript-tuple basically it behaves similarly to .slice() but in a type way – themajashurka Oct 24 '22 at 08:15
  • Please see [this](https://stackoverflow.com/questions/69089549/typescript-template-literal-type-how-to-infer-numeric-type#answer-69090186) answer. You can cast it like [here](https://tsplay.dev/N5zjBm) – captain-yossarian from Ukraine Oct 24 '22 at 08:16
  • I stripped some bit from your answer for this specific tuple purpose, and this one works perfectly: ```type ParseInt = T extends `${infer Digit extends number}` ? Digit : never``` Thank you so much, ```infer``` rules! – themajashurka Oct 24 '22 at 08:25

0 Answers0