如何使用具有元组类型的通用休息元素? [英] How to use generic rest element with tuple types?

查看:37
本文介绍了如何使用具有元组类型的通用休息元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript 给我一个通用元组其余元素的错误

TypeScript is giving me an error with a generic tuples rest element

type Tuple<Value extends any[]> = [...Value];

错误:

$ tsc
src/index.ts:1:36 - error TS2574: A rest element type must be an array type.

1 type Tuple<Value extends any[]> = [...Value];

我在这里遗漏了什么?

  • 打字稿版本:typescript@3.1.6
type Tuple<HEAD, TAIL extends any[]> = [HEAD, ...TAIL];

不起作用,尽管这有效:

doesn't work, although this works:

type Tuple<Value extends any[]> = [...any[]];

推荐答案

针对 TS4.0+ 的更新.TypeScript 4.0 引入了对 variadic 的支持元组类型,所以这个问题中的代码应该像编写的那样工作,而无需根据函数参数改写您的操作.万岁!

UPDATE for TS4.0+. TypeScript 4.0 introduced support for variadic tuple types, so the code in this question should work as written, without needing to reword your operation in terms of function parameters. Hooray!

TS3.9- 答案:

您唯一缺少的是这种推断目前不受支持.也许它会出现在 TypeScript 的未来版本中.幸运的是,仍然有一种方法可以通过在 函数参数,因为从 TypeScript 3.0 开始,有一种方法可以在元组/数组类型和函数参数之间进行转换,您可以使用 infer 根据参数类型的需要.

The only thing you're missing is that such inference isn't currently supported. Maybe it will be in a future version of TypeScript. Luckily there is still a way to do what you want by expressing the desired operation in terms of one on function parameters, since as of TypeScript 3.0, there is a way to convert between tuple/array types and function parameters, and you can use infer as desired on parameter types.

这是 Tail 的一种可能实现:

Here's one possible implementation of Tail:

type Tail<T extends any[]> = 
  ((...t: T) => void) extends ((x: any, ...u: infer U) => void) ? U : never;

type TestTail = Tail<[1,2,3,4]>; // [2,3,4]

请注意,您将元组/数组类型 T 扩展到参数列表,然后将第一个参数之后的所有内容推断为另一个元组/数组剩余类型.

Notice that you take the tuple/array type T, spread it to a parameter list, then infer everything after the first parameter as another tuple/array rest type.

同样,您可以以我称之为 Tuple>缺点:

Similarly, you can implement your Tuple in a way that I'd call Cons:

type Cons<H, T extends any[]> = 
  ((h: H, ...t: T) => void) extends ((...u: infer U) => void) ? U : never;

type TestCons = Cons<string, [number, boolean]>; // [string, number, boolean]

我将把 Head 作为练习留给你(当人们想要显得聪明而不是懒惰时,这就是他们所说的).

And I'll leave Head as an exercise for you (that's what people say when they want to seem smart instead of lazy).

无论如何,希望能帮助你取得进步.祝你好运!

Anyway, hope that helps you make progress. Good luck!

这篇关于如何使用具有元组类型的通用休息元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆