Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect at least one argument for variadic method in TypeScript

Tags:

typescript

tsc

I have a method like so:

  getValues(...args: Array<string>) : Array<any> {
    return args.map(k => {
      return this.shared.get(k);
    });
  }

I use the method like this:

const c = b.getValues(); // compiles

it's actually incorrect in my case to pass no arguments, it only makes sense if at least one argument is passed.

Is there a way to tell TypeScript that at least one argument needs to be passed?

like image 802
Alexander Mills Avatar asked Sep 15 '25 16:09

Alexander Mills


2 Answers

You can add an overload that has a mandatory parameter to force callers to specify at least one value, but keep the implementation signature using just a rest parameter (keeping your implementation the same)

getValues(mandatory: string, ...args: Array<string>): Array<any>
getValues(...args: Array<string>): Array<any> {
    return args.map(k => {
        return this.shared.get(k);
    });
}
like image 112
Titian Cernicova-Dragomir Avatar answered Sep 18 '25 10:09

Titian Cernicova-Dragomir


You can use a tuple-like array with variadic arguments:

getValues(...args: [string, ...string[]])
like image 35
chetbox Avatar answered Sep 18 '25 10:09

chetbox