Home > Blockchain >  Declare array structure for function (...args)
Declare array structure for function (...args)

Time:03-23

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...

CodePudding user response:

It indeed is using a spread inside the arguments type:

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

Try for yourself and see:

Playground

  • Related