如何在JSDoc中记录解构参数?

4
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中定义了参数类型?

2个回答

2

这并不完美地工作,因为这是一个未解决的问题,但你可以做的最好的事情是:

/**
 * @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的屏幕录像,展示它可以解释这个文档块。(我相信其他IDE也可以做到同样的事情)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接