#Variadic tuple-like function arguments

8 messages · Page 1 of 1 (latest)

sick gazelle
#

Hi there,

I'm trying to implement a type-safe version of a vararg function whose arguments are defined in a specific order.

So far I came to the following type declaration:

type PairArgs<L, R> = [L, R, ...PairArgs<L, R>[]];

function foo(arg1: string, ...rest: PairArgs<string, number>);

// Usage:
foo("arg1", "one", 1, "two", 2, "three", 3);

But this only solves the problem for paired arguments (let's call it TupleOfTwo).

Now, I want to introduce a generic version of it (TupleOfN), so I'm trying this:

type TupleArgs<Types extends unknown[]> = [...Types, ...TupleArgs<Types>[]];

but it doesn't work (Type alias TupleArgs circularly references itself.

Is there any way to do a generic N-ary version of such a tuple?

noble jolt
#

FWIW i think usage of foo would be this instead of what you wrote:

foo("arg1", "one", 1, ["two", 2], ["three", 3])

you can do the same with TupleArgs like so:

type TupleArgs<Types extends unknown[]> = [...Types, ...Types[]];

declare function bar(arg1: string, ...rest: TupleArgs<[string, number, boolean]>): void;
bar("arg1", "one", 1, true, ["two", 2, true])
sick gazelle
#

Is there any way to constrain a vararg function with a plain repeatable pattern of argument types?

#
foo(string, number, string, number, string, number, ...)
dense flax
sick gazelle
dense flax
#

shouldnt jcalz be the one that gets the rep