Learn TypeScript28 (infer recursion)

there is such a type

type Arr = [1, 2, 3, 4]

Hope to become through a ts tool

type Arr = [4,3,2,1]

full code

type Arr = [1, 2, 3, 4]

type ReveArr<T extends any[]> = T extends [infer First, ...infer rest] ? [...ReveArr<rest>, First] : T

type Res = ReveArr<Arr>

 The specific idea is to first use the generic constraint to constrain that only things of the array type can be passed in, then extract the first one from the array, put it at the end of the new array, and repeat this operation to form a recursion that satisfies the end condition and returns the type

Guess you like

Origin blog.csdn.net/qq1195566313/article/details/126449668