问题
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