问题描述
为什么这会产生错误其余元素类型必须是数组类型."?
Why this produces an error "A rest element type must be an array type."?
type QWE<T extends [number, string]> = [boolean, ...T]
^^^^ the error is here
推荐答案
在 3.0 之前,我们无法将元组或泛型类型参数传播给函数,因此必须实现这一点.类似地,元组中的其余部分目前仅支持数组,没有人实现将其他元组传播到给定元组的其余部分的能力,我猜想实现它需要大量的努力和复杂性.
Before 3.0 we could not spread tuples or generic type arguments to a function and this had to be implemented. Similarly, rest in tuples currently only support arrays, nobody implemented the ability to spread other tuples into the rest of a given tuple, and I'm guessing implementing it would require significant effort and complexity.
要在另一个已知元组的末尾添加一个元组,我们可以使用将元组扩展为一个函数,然后将参数类型提取为元组的能力.
To add a tuple at the end of another known tuple we can use the ability to spread a tuple tu a function and then extract the argument types as a tuple.
type ArgumentTypes<T extends (...a: any) => any> =
T extends (...a: infer A) => any ? A : never;
type QWE<T extends [number, string]> =
ArgumentTypes<(a: boolean, ...r: T) => void>
type R = QWE<[number, string]>
在开始时添加元组更成问题,我相信有一些非常不推荐的 hacks 可以使用递归类型别名来实现这一点.您还可以定义多个条件以支持一个元组中的多个元素,但如果可能,我会避免使用它
Adding the tuple at the start is more problematic, I believe there are some very unrecommended hacks that can achieve this using recursive type aliases. You can also define multiple conditions to support up to a number of elements in a tuple, but I would avoid it if possible
这篇关于打字稿:如何将项目添加到元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!