代码之家  ›  专栏  ›  技术社区  ›  doberkofler

如何验证typescript中的参数个数

  •  0
  • doberkofler  · 技术社区  · 6 年前

    我(只)使用 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. 在arrow函数中引用时。

    如何(总是)验证typescript中的参数数量?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Matt H    6 年前

    您发布的代码段对我来说似乎没有相同的错误。如果我把它改成箭头函数,我会看到这个错误:

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

    解决这个问题。

        2
  •  2
  •   Karol Majewski    6 年前

    您还可以在编译时强制实现函数的arity:

    const myFunction = (...args: [any]) => {
      /* ... */
    }
    
    myFunction(1);    // OK
    myFunction(1, 2); // Compile-time error