【问题标题】:How to document destructured parameters in JSDoc?如何在 JSDoc 中记录解构参数?
【发布时间】:2022-01-01 01:17:48
【问题描述】:
async function userInformation({ userId, token }) {
  const body = {
    user: userId
  };

  const headers = {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  const url = 'https://example.com/api/users';

  const data = await axios.post(url, headers, qs.stringify(body));

  return data;
}

考虑这段代码 我应该如何为这个函数编写 jsdoc? 如何保证jsdoc中定义了参数类型?

【问题讨论】:

    标签: javascript node.js documentation jsdoc


    【解决方案1】:

    这并不完美,因为它是 open issue,但您能做的最好的事情是:

    /**
     * @param {{ userId: number, token: string }} info
     * @param {string} info.userId this description appears
     * @param {number} info.token this also appears on hover
     */
    async function userInformation({ userId, token }) {
      const body = {
        user: userId
      };
    
      const headers = {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/x-www-form-urlencoded'
      };
    
      const url = 'https://example.com/api/users';
    
      const data = await axios.post(url, headers, qs.stringify(body));
    
      return data;
    }
    

    你最终写了两次信息,但它似乎确保 VSCode 知道发生了什么。

    【讨论】:

      【解决方案2】:

      即使您已经解构了参数,它们仍然来自一个来源(一个对象),这是您需要记录的。

      我建议使用@typedef 来描述对象的形状,并在记录函数时将其用作类型。

      /**
       * @typedef {object} Credentials
       * @property {number} userId
       * @property {string} token
       */
      
      /**
       * @param {Credentials} credentials
       */
      async function userInformation({ userId, token }) {
        // ...
      }
      

      这是来自 VS Code 的截屏视频,显示它可以解释这个 doc 块。 (我相信其他 IDE 也可以这样做)

      【讨论】:

        猜你喜欢
        • 2020-05-21
        • 2018-01-29
        • 2022-01-16
        • 1970-01-01
        • 2021-11-03
        • 2017-11-22
        • 1970-01-01
        • 2013-04-07
        • 1970-01-01
        相关资源
        最近更新 更多