tengobash tengobash - 1 year ago 116
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

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

Answer Source

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));        
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download