N参数 vs. 单参数
N-Params vs. Single Param

原始链接: https://www.carlos-menezes.com/single-param-functions/

在TypeScript(以及任何不支持命名参数的语言)中编写函数时,参数传递方式有两种:单个参数传递(n个参数)或将参数组合成单个对象。虽然两者都有效,但我还没找到对象参数不是更好选择的情况。 例如,调用创建用户的函数:`const signup = () => { // ... createUser("John", "Doe", 28, true); // ... };` 一眼就能看出每个值代表什么吗?你只能猜测:28是什么?true又是什么?参数越多,代码就越脆弱和混乱。 相反,考虑使用对象参数: `type TCreateUserInput = { firstName: string; lastName: string; age: number; isActive: boolean; }; const signup = () => { // ... createUser({ firstName: "John", lastName: "Doe", age: 28, isActive: true }); // ... };` 一目了然,无需猜测参数顺序。你的代码具有自文档性。此外,TypeScript 提供了完整的自动补全和类型安全。

这篇 Hacker News 讨论帖讨论了在函数定义中使用单个参数对象代替多个独立参数的做法,尤其是在 JavaScript 中。 原作者 carlos-menezes 倡导这种方法,因为它可以提高代码可读性、变量命名的一致性以及代码的自文档化程度。评论者们就其优缺点展开了辩论。一些人表示赞同,强调了这种方法在扩展性和 TypeScript 类型安全方面的优势。一位用户提到返回值缺乏固有的名称,使得函数目的不够清晰。另一些人认为,在 C/C++ 等语言中,这种模式可能会由于结构体与寄存器相比可能造成的开销而对性能产生负面影响。另一位用户建议编译器理想情况下可以优化掉这种低效。许多人认为这是一种个人偏好,取决于具体的上下文和项目复杂性,并链接了 Google 的指导方针:“避免过长的参数列表”。
相关文章
  • 别害怕类型 2025-03-22
  • (评论) 2025-03-22
  • 解析,不验证 (2019) 2024-07-23
  • (评论) 2024-07-26
  • (评论) 2024-07-23

  • 原文

    When writing functions in TypeScript (and, truthfully, any language that does not support named parameters), you either pass arguments individually (n params) or group them into a single object. While both are valid, I am yet to find a case were object parameters aren't the better choice.

    Say you call a function which creates a user:

    const signup = () => {
      // ...
      createUser("John", "Doe", 28, true);
      // ...
    };
    

    At a glance, can you tell what each value means? You’re left guessing: what’s 28? What’s true? The more parameters you add, the more brittle and confusing this becomes.

    Instead, consider using an object parameter:

    type TCreateUserInput = {
      firstName: string;
      lastName: string;
      age: number;
      isActive: boolean;
    };
    
    const signup = () => {
      // ...
      createUser({ firstName: "John", lastName: "Doe", age: 28, isActive: true });
      // ...
    };
    

    No guessing. No worrying about the order. Your code is self-documenting. Plus, TypeScript gives you full autocompletion and type safety.

    联系我们 contact @ memedata.com