Expect at least one argument for variadic method in TypeScript

旧巷老猫 提交于 2020-12-12 08:58:11

问题


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?


回答1:


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);
    });
}


来源:https://stackoverflow.com/questions/51374490/expect-at-least-one-argument-for-variadic-method-in-typescript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!