Home > Enterprise >  Typescript function overload type inference with deconstructed rest parameter
Typescript function overload type inference with deconstructed rest parameter

Time:11-26

Given the following overloaded function:

foo(tool: 'a', poaram: boolean, poarama: number): boolean
foo(tool: 'b', paramo: string, paramoa: string): boolean
foo(tool: 'a' | 'b', ...args: any[]): boolean {
    if (tool === 'a') {
        const [ poaram, poarama ] = args

    }

    return false
}

Is there any way to have poaram and poarama not be typed as any but as boolean and number respectively?

I am aware of Tuples in rest parameters and spread expressions, but I fail to see the connection to my use case above.

CodePudding user response:

If you are allowed to use TypeScript nightly (4.6) you can consider this solution:


function foo(...args: ['a', boolean, number] | ['b', string, string]): boolean {
    const [fst, scd, thrd] = args;
    if (fst === 'a') {
        const x = scd; // boolean
        const y = thrd // number

    }

    return false
}

Playground Or even without rest parameters:


function foo([first, second, third]: ['a', boolean, number] | ['b', string, string]): boolean {
    if (first === 'a') {
        const x = second; // boolean
        const y = third // number

    }

    return false
}

Above feature was added here TypeScript/pull/46266

If you are not allowed, you should avoid tuple destructure:


function foo(...args: ['a', boolean, number] | ['b', string, string]): boolean {
    if (args[0] === 'a') {
        const x = args[1]; // boolean
        const y = args[2] // number

    }

    return false
}

CodePudding user response:

You could pick one of these for your function's implementation type:

foo(tool: 'a'|'b', ...args: [boolean, number]|[string, string]): boolean { // or
foo(tool: 'a'|'b', arg1: boolean|string, arg2: number|string): boolean {
  • Related