本文介绍了如何在打字稿中编写“反转"类型以反转元组的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
type a = [1,2,3]
type Invert<T extends any[] & {'0': any}> = ???
type b = Invert<a> // should yield [3,2,1]
我一直想弄清楚元组的 Invert
类型的定义,也是 Init
和 Last
类型,尽管它们可以相互构造
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
我尝试过的:
- 在函数参数定义中定位类型并推断
Rest
部分,这种方法只得到带有rest参数的Tail
部分
- position the type in a function param definition and infer the
Rest
part, this approach only got theTail
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>
一些解释:
- 类型别名
Reverse
中的直接引用类型Reverse
会导致循环引用错误. - wrap
Reverse
type in function type (()=> Reverse
) 将选择退出循环引用错误 - 如果类型表达式可以静态解析,编译器会尝试解析它,所以
ReturnTypeTup<L,[F,...R]>>
不会成功,但是ReturnType
会做
- direct reference type
Reverse
in typealiasReverse
will result in circularly references error. - wrap
Reverse
type in function type (()=> Reverse
) will opt-out the circularly references error - 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
这篇关于如何在打字稿中编写“反转"类型以反转元组的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!