0

Just to illustrate what I mean by "unpacking", consider the following example

function simpleFunc(a: number, b: string): void { /* ... */ }
function simpleProxy(args: [number, string]) {
    simpleFunc(...args)
}

This works just fine, with typescript mapping [number, string] to (a: number, b: string). I have a use-case where I have to do something similar with a more complex function which has overloaded signatures, like so:

function overloadFunc(name: string): void
function overloadFunc(name: string, content: number): void
function overloadFunc(content: number): void
function overloadFunc(name_or_content: string | number, maybe_content?: number): void {
    /* ... */
}

Now I can't make unpacking to compile. I tried this:

function overloadProxy1(args: [string] | [string, number] | [number]) {
    overloadFunc(...args);
    //           ^^^^^^^
    // Expected 1-2 arguments, but got 0 or more.(2556)
    // ... An argument for 'name' was not provided.
}

And this:

function overloadProxy2(args: [string | number, number?]) {
    overloadFunc(...args);
    //           ^^^^^^^
    // Argument of type 'string | number' is not assignable to parameter of type 'string'.
    // Type 'number' is not assignable to type 'string'.(2345)
}

Is there a way to make this work ? If not, is this documented somewhere ?

Antoine
  • 13,494
  • 6
  • 40
  • 52

1 Answers1

1

The answer is this lovely Parameters type utility:


// This way if you want to call it like overloadProxy1(['name'])
function overloadProxy1(args: Parameters<typeof overloadFunc>) {
  // ...
}

// Or this way if you want to call it like overloadProxy1('name')
function overloadProxy1(...args: Parameters<typeof overloadFunc>) {
  // ...
}

Link to TypeScript playground

Link to documentation

Antoine
  • 13,494
  • 6
  • 40
  • 52
Ján Jakub Naništa
  • 1,880
  • 11
  • 12