简体   繁体   English

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

[英]How to document destructured parameters in JSDoc?

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

Consider this code How should I write jsdoc for this function?考虑这段代码我应该如何为这个 function 编写 jsdoc? How to ensure that the parameters types were defined in jsdoc?如何确保在 jsdoc 中定义了参数类型?

Even if you have destructured your parameters, they still came from one source (an object) which is what you need to document.即使您已经解构了参数,它们仍然来自您需要记录的一个来源(一个对象)。

I'd recommend using @typedef to describe the shape of the object and use it as a type when documenting your function.我建议使用@typedef来描述 object 的形状,并在记录 function 时将其用作类型。

/**
 * @typedef {object} Credentials
 * @property {number} userId
 * @property {string} token
 */

/**
 * @param {Credentials} credentials
 */
async function userInformation({ userId, token }) {
  // ...
}

Here's a screencast from VS Code showing that it can interpret this doc block.这是来自 VS Code 的截屏视频,显示它可以解释这个 doc 块。 (I'm sure other IDEs can do the same) (我确信其他 IDE 也可以这样做)

在此处输入图像描述

This doesn't work perfectly, as it's an open issue but the best you can do is:这并不完美,因为它是一个开放的问题,但你能做的最好的是:

/**
 * @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;
}

You end up writing information twice, but it seems to make sure VSCode knows whats going on.你最终写了两次信息,但它似乎确保 VSCode 知道发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM