tengobash tengobash - 4 months ago 10
TypeScript Question

Force at least one argument for rest parameter

I searched for an answer for this but did not find an answer:

Is there a way to force at least one argument for a rest parameter?

In the code below all three calls to

logArray
are valid but I want the first one to fail.

function logArray(...elements: number[]) {
elements.forEach(x => console.log(x));
}

logArray(); // should fail but works
logArray(1);
logArray(1,2);

Answer

One possible solution could be just adding a regular parameter in front of the rest parameter and concatenating it back in the function body like so

function logArray(e1: number ,...erest: number[]) {
    [e1, ...erest].forEach(x => console.log(x));        
}