简体   繁体   中英

Typescript unpacking arguments to overloaded function

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM