Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 15, 2022 07:37 pm GMT

Typescript Exceed Recursion Limitation

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'] // 999type B = CreateArrayWithLengthX<1000>['length'] // any

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

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

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


Original Link: https://dev.to/tylim88/typescript-exceed-recursion-limitation-18pm

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To