How to document destructured parameters in JSDoc?

Viewed 697
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 ? How to ensure that the parameters types were defined in jsdoc ?

2 Answers

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.

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} 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. (I'm sure other IDEs can do the same)

enter image description here

Related