Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How to add an item to a tuple?

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
like image 592
Nurbol Alpysbayev Avatar asked Dec 11 '22 04:12

Nurbol Alpysbayev


1 Answers

If someone can find it useful, this is a version of Titian's type, with an improvement covering some more cases:

type R = TupleUnshift<boolean, [number, string]> // [boolean, number, string]


type TupleUnshift<A, B extends [...any[]]> = ((a: A, ...r: ForcedTuple<B>) => void) extends (...a: infer R) => any ? R : never

type ForcedTuple<T> =
    T extends [
        infer A,
        infer B,
        infer C,
        infer D,
        infer E,
        infer F,
        infer G,
        infer H,
        infer I,
        infer J,
        infer K,
        infer L,
        infer M,
        infer N,
        infer O,
        infer P,
        infer Q,
        infer R,
        infer S,
        infer T,
        infer U,
        infer V,
        infer W,
        infer X,
        infer Y,
        infer Z
    ]
    ?
    [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
    : T
like image 184
Nurbol Alpysbayev Avatar answered Feb 23 '23 17:02

Nurbol Alpysbayev