DEV Community

Acid Coder
Acid Coder

Posted on • Updated on

Typescript Recursion: It Is Over 999!

This is a proof of concept post, personally I do not find any use of this, yet

Typescript recursion stop at 49th or 999th loop

type CreateArrayWithLengthX<
    LENGTH extends number,
    ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
    ? ACC
    : CreateArrayWithLengthX<LENGTH, [...ACC, 1]>

type A = CreateArrayWithLengthX<999>['length'] // 999

type B = CreateArrayWithLengthX<1000>['length'] // any
Enter fullscreen mode Exit fullscreen mode

Image description

playground

This is not good if you want to dynamically generate array type with length more than 999

solution is to add another dimension to loop more than 999 times

type CreateArrayWithLengthX<
    LENGTH extends number,
    ACC extends unknown[] = [],
> = ACC['length'] extends LENGTH
    ? ACC
    : CreateArrayWithLengthX<LENGTH, [...ACC, 1]>

type Exceed999<
    ARR extends 1[],
> = [...ARR['length'] extends 0 ? []: [...CreateArrayWithLengthX<999>,...Exceed999<ARR extends [...infer S extends 1[], infer P] ? S : never>]]

type V = Exceed999<CreateArrayWithLengthX<10>>['length'] // 10x999 = 9990
Enter fullscreen mode Exit fullscreen mode

playground

now you can dynamically create array type with length larger than 999

however keep in mind that the max length of an array type is 10,000

It is possible to create an array with any length less than 10,000, not just the multiplier of 999, but that would involve a lot of works and I want to keep thing simple here

Top comments (0)