Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a jsdoc type to a destructured variable? (VSCode)

So I have a response object with a data property. For this example, its data is of type text. I want the data property, and I want VSCode to recognize it types so that I can get some of that IntelliSense love.

const response = await someRequest();
const {data} = response;

First I try:

const response = await someRequest();

/** @type {string} */
const {data} = response;

Nope, so then I try:

const response = await someRequest();

const {
  /** @type {string} */
  data,
} = response;

that didn't work either.

Then I try:

/**
 * @typedef {Object} Response
 * @property {string} data
 */

/** @type {Response} */
const response = await someRequest();

const { data } = response;

That worked!

I'm not sure how much of a difference it makes, but I'm using VSCode September 2020 (version 1.50).

Edits: I changed how my question ended because it turned out that my final example actually works...

like image 318
Ryan Varley Avatar asked Sep 05 '25 03:09

Ryan Varley


2 Answers

The simple way to jsdoc it is as follows:

/** @type {{data:string}} */
const response = await someRequest();
const {data} = response;

Even better if you have control of the someRequest function is to jsdoc it like so:

/** @returns {Promise<{data:string}>} */
async function someRequest() {
  return {data: ""};
}

const response = await someRequest();
const {data} = response;

Finally, for completeness, you can inline it a few places. Here's an example:

const {data} = /** @type {{data:string}} */ (await someRequest()) || {};
like image 81
JPC Avatar answered Sep 07 '25 19:09

JPC


/**
 * @typedef {Object} Response
 * @property {string} data
 */

/** @type {Response} */
const response = await someRequest();

const { data } = response;

I didn't think this was working, but it is, so I'm marking it as the answer.

Thanks to Dolly for her comment with how to document a deconstructed variable with jsdoc. It wasn't an exact fit, but it does answer my question.

like image 35
Ryan Varley Avatar answered Sep 07 '25 21:09

Ryan Varley