我(仅)使用arguments
在传递给函数的参数数量无效时抛出错误。
const myFunction = (foo) => {
if (arguments.length !== 1) {
throw new Error('myFunction expects 1 argument');
}
}
不幸的是,在 TypeScript 中,我在箭头函数中引用时The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression.
出现错误。
如何(始终)验证 TypeScript 中的参数数量?
您发布的代码片段对我来说似乎没有相同的错误。 如果我将其更改为箭头函数,我确实会看到该错误:
const myFunction = (foo) => {
if (arguments.length !== 1) {
throw new Error('myFunction expects 1 argument');
}
}
您可以尝试执行以下操作:
const myFunction = (...foo) => {
if (foo.length !== 1) {
throw new Error('myFunction expects 1 argument');
}
}
要解决此问题。
您还可以在编译时强制执行函数的 arity:
const myFunction = (...args: [any]) => {
/* ... */
}
myFunction(1); // OK
myFunction(1, 2); // Compile-time error