2

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.

1
  • You need to make them all part of rest arguments. See example tsplay.dev/w14nyW . Let me know if it works for you. You don't even need to overload your function in this case. Please also keep in mind that it works only with TS nightly, 4.6 Commented Nov 25, 2021 at 10:59

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

To assign the first argument to tool, foo([tool, ...args]: ['a', boolean, number] | ['b', string, string]): boolean should work too, right?
@DustInCompetent it looks like it does not work that way. I' can't say that I'm very familiar with this new feature, hence I'm unable to provide you with thorough explanation. Just did not have a chance to dig into it. It is not even released yet
0

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 {

1 Comment

That's true. But I was looking for a way without explicitly writing out the type of ...args :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.