检查函数是否在 module.exports 中有多个参数
Check if function has multiple arguments in module.exports
我想做这样的事情:
module.exports = (obj) => {
if (arguments.length > 1) {
throw new Error('Must only pass in single argument');
}
}
当我记录参数时,我得到了关于模块本身的元数据,但看不到传入的参数。有没有办法检查是否传入了其他参数?
这是我的测试:
it('should reject multiple arguments', () => {
expect(fn({ data: 1}, { data: 2})).to.throw(Error, 'Too many inputs');
});
arguments
不适用于 ES6 箭头函数。
试试这个 ...args
function f(a, b, ...args) {
}
来源:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/rest_parameters
如MDN's page on arrow function所述:
An arrow function expression has a shorter syntax than a function expression and does not bind its own this
, arguments
, super
, or new.target
.
换句话说,要检查箭头函数是否获得比预期更多的参数,使用 arguments
不起作用(与普通函数一样),因此您应该使用 rest parameters :
const fn = (obj, ...restArgs) => {
if(restArgs.length > 0) {
// got more arguments than expected
throw new Error('Must only pass in single argument');
}
};
正如其他人提到的,箭头函数是导致您出现问题的原因。
但是,在这种情况下,为了正确定义您的 API,使用剩余参数并不是一个好的解决方案。
为了保持与你想要的兼容(显示函数只接受一个参数),你应该这样做:
module.exports = function (obj) {
if (arguments.length > 1) {
throw new Error('Must only pass in single argument');
}
}
在你的箭头函数中,参数实际上与你不期望的东西相关联。
请参阅 https://github.com/unional/some-issues/tree/so-arrow-arguments 了解它的实际作用。
我想做这样的事情:
module.exports = (obj) => {
if (arguments.length > 1) {
throw new Error('Must only pass in single argument');
}
}
当我记录参数时,我得到了关于模块本身的元数据,但看不到传入的参数。有没有办法检查是否传入了其他参数?
这是我的测试:
it('should reject multiple arguments', () => {
expect(fn({ data: 1}, { data: 2})).to.throw(Error, 'Too many inputs');
});
arguments
不适用于 ES6 箭头函数。
试试这个 ...args
function f(a, b, ...args) {
}
来源:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/rest_parameters
如MDN's page on arrow function所述:
An arrow function expression has a shorter syntax than a function expression and does not bind its own
this
,arguments
,super
, ornew.target
.
换句话说,要检查箭头函数是否获得比预期更多的参数,使用 arguments
不起作用(与普通函数一样),因此您应该使用 rest parameters :
const fn = (obj, ...restArgs) => {
if(restArgs.length > 0) {
// got more arguments than expected
throw new Error('Must only pass in single argument');
}
};
正如其他人提到的,箭头函数是导致您出现问题的原因。
但是,在这种情况下,为了正确定义您的 API,使用剩余参数并不是一个好的解决方案。
为了保持与你想要的兼容(显示函数只接受一个参数),你应该这样做:
module.exports = function (obj) {
if (arguments.length > 1) {
throw new Error('Must only pass in single argument');
}
}
在你的箭头函数中,参数实际上与你不期望的东西相关联。 请参阅 https://github.com/unional/some-issues/tree/so-arrow-arguments 了解它的实际作用。