Search code examples
typescripttuplestype-level-computation

how to write an `Invert` type in typescript to invert the order of tuples


type a = [1,2,3]
type Invert<T extends any[] & {'0': any}> = ???
type b = Invert<a> // should yield [3,2,1]

I am stucked to figure out the definition of Invert type of a tuple, also an Init and Last type, although they may be constructed of each others

what I have tried:

  1. position the type in a function param definition and infer the Rest part, this approach only got the Tail part with rest params

Solution

  • as of typescript 4.0 code to approach a Reverse type is much easier than before, saying

    type Reverse<T extends any[], R extends any[] = []> =  ReturnType<T extends [infer F, ...infer L] ? () => Reverse<L,[F,...R]> : () => R>
    

    some explanation:

    1. direct reference type Reverse in typealias Reverse will result in circularly references error.
    2. wrap Reverse type in function type (()=> Reverse) will opt-out the circularly references error
    3. if type expression could resolve staticly, the compiler will try to resolve it, so ReturnType<() => Tup<L,[F,...R]>> wont do the trick, but ReturnType<ConditionalType> will do