PEZO
PEZO

Reputation: 521

Typescript: how to map array of types to distinct arguments via advanced types?

Current API

type Array1 = [MyArgs   , MyExample] // assuming types `MyArgs` and `MyExample` exist
type Array2 = [MyExample, MyArgs   ]
type ValidArray = Array1 | Array2 | ... // assuming no validArray like [MyArgs, MyArgs] and [MyExample, MyExample]

const f = (va: ValidArray) => {...}
const myargs    : MyArgs    = ...
const myexample : MyExample = ...

f([myargs,myexample])

Instead of what you see in the last row of the current API, I want this API:

f(myargs,myexample)

without losing the information, that the 2 arguments together have to be one of the type of the enumerated arrays in ValidArrays

So, for example I don't want to accept these as valid argument lists:

f(myargs   ,myargs   )
f(myexample,myexample)

I assume there is an advanced typescript technique to map (or spread?) the arrays of types to the argument list like that, but I couldn't find it out.

Upvotes: 1

Views: 54

Answers (1)

Gerrit Begher
Gerrit Begher

Reputation: 403

If I understood your question (and additional comment) correctly, const fn = (...args: [...ValidArray, ...any[]]) => ... should be what you want. (Playground link)

type Arr1 = [1, 2]
type Arr2 = ["A", "B"]

type ValidArray = Arr1 | Arr2


const fn = (...args: [...ValidArray, ...any[]]): number => args.length

// These work
const test1 = fn(1, 2)
const test2 = fn("A", "B")
const test3 = fn("A", "B", "and", "other", "args")

// Type errors
const fail1 = fn(1, "B")
const fail2 = fn("A", 2)
const fail3 = fn(1, 1, "and", "other", "args")

Upvotes: 1

Related Questions