类型以反转元组的顺序

类型以反转元组的顺序

本文介绍了如何在打字稿中编写“反转"类型以反转元组的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我一直想弄清楚元组的 Invert 类型的定义,也是 InitLast 类型,尽管它们可以相互构造

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

我尝试过的:

  1. 在函数参数定义中定位类型并推断Rest部分,这种方法只得到带有rest参数的Tail部分
  1. position the type in a function param definition and infer the Rest part, this approach only got the Tail part with rest params

推荐答案

从 typescript 4.0 开始处理 Reverse 类型的代码比以前容易得多,说

as of typescript 4.0code 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>

一些解释:

  1. 类型别名Reverse中的直接引用类型Reverse会导致循环引用错误.
  2. wrap Reverse type in function type (()=> Reverse) 将选择退出循环引用错误
  3. 如果类型表达式可以静态解析,编译器会尝试解析它,所以 ReturnTypeTup<L,[F,...R]>> 不会成功,但是ReturnType 会做
  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, butReturnType<ConditionalType> will do

这篇关于如何在打字稿中编写“反转"类型以反转元组的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:29