0

Is there a way specify that function foo can accept unlimited number of arguments as an array of 3 numbers, but last parameter must be a number?

function foo(...args:number[]|number[][])
{
  const first = args[0] as [number, number, number],
        second = args[1] as [number, number, number],
        last = args[args.length-1] as number;
}

foo([1,2,3], [4,5,6], [7,8,9], 123);

The code above give error:

Argument of type '[number[], number[], number[], 123]' is not assignable to parameter of type 'number[] | number[][]'.
  Type '[number[], number[], number[], 123]' is not assignable to type 'number[][]'.
    Type 'number[] | 123' is not assignable to type 'number[]'.
      Type 'number' is not assignable to type 'number[]'.

P.S. I understand it would be simpler just accept two parameters one of which is array of arrays, but I just want to know if this is possible...

1 Answer 1

1

It indeed is using a spread inside the arguments type:

function foo(...args: [...number[][], number]) { ... }

Try for yourself and see:

Playground

Sign up to request clarification or add additional context in comments.

1 Comment

Unexpectedly spread inside the argument type doesn't have to be last in the list... Thank you!

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.