2

It should work like:

type SpecifiedLengthTuple<T, L extends number> = ???

type tupleOfThreeStrings = SpecifiedLengthTuple<string, 3> // [string, string, string]

If someone wonders, I want this to solve this question: Typescript: increment number type

with the help of TupleUnshift type from here:

by checking ['length'] of a resulted (unshifted) tuple.

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • 3
    [Not officially](https://github.com/Microsoft/TypeScript/issues/26223). You can come up with a recursive definition that even compiles using a trick, but in practice the compiler will stop checking properly after some depth (6? 20? something like that) so a hardcoded list like `[[],[any],[any,any],...]` is probably the best you can do right now. – jcalz Jan 17 '19 at 20:08
  • Hi @jcalz Thank you. Can you please also check [this](https://stackoverflow.com/questions/54243565/typescript-how-to-make-a-recursion) related question? It's about recursion, but I think it would be OK if the limit is 20 or something. At least I want to know how to defeat the recursion (circular references) error. – Nurbol Alpysbayev Jan 17 '19 at 20:12

1 Answers1

1

You have to define PrependToTuple generic with takes tuple [...T] and Item and returns [I, ...T]

type PrependTuple<A, T extends Array<any>> = 
  (((a: A, ...b: T) => void) extends (...a: infer I) => void ? I : [])

You can use recursive call that returns tuple when length is equals N and return accumulated tuple with prepend item if is not equals N

type SpecifiedLengthTuple<T, N extends number, L extends Array<any> = []> = {
  true: L;
  false: SpecifiedLengthTuple<T, N, PrependTuple<T, L>>;
}[L['length'] extends N ? "true" : "false"];

type Result = SpecifiedLengthTuple<boolean, 3>; // [boolean, boolean, boolean]

Playground

Przemyslaw Jan Beigert
  • 2,351
  • 3
  • 14
  • 19