Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to document destructured parameters in JSDoc? [duplicate]

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 ?

like image 558
Arv Avatar asked Sep 19 '25 22:09

Arv


2 Answers

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

like image 132
customcommander Avatar answered Sep 21 '25 12:09

customcommander


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.

like image 39
AncientSwordRage Avatar answered Sep 21 '25 11:09

AncientSwordRage