Typescript: How to add an item to a tuple?

前端 未结 3 1707
长情又很酷
长情又很酷 2020-12-21 05:23

Why this produces an error \"A rest element type must be an array type.\"?

type QWE = [boolean, ...T]
                              


        
3条回答
  •  醉话见心
    2020-12-21 05:55

    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 any> =
        T extends (...a: infer A) => any ? A : never;
    type QWE = 
        ArgumentTypes<(a: boolean, ...r: T) => void>
    
    type R = QWE<[number, string]>
    

    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

提交回复
热议问题