Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you get the return type of a function in jsdoc?

I have two files src/a.js src/b.js.I want the type of response to be the return value of the request function.

If in Typescript I could have written this ⬇️。Is there a similar syntax in jsdoc?

I don’t want to use @typedef to define an additional type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// src/a.ts

export function request() {
  return Promise.resolve({
    name: "William",
  });
}


// src/b.ts

import { request } from "./a";

export function handleResponse(response: ReturnType<typeof request>) {}

src/a.js

export function request() {
  return Promise.resolve({
    name: "William",
  });
}

src/b.js

/**
 * @param {???} response
 * @returns {void}
 */
export function handleResponse(response) {}

>Solution :

To get a similar effect in JSDoc without using @typedef, you can use import() syntax in the JSDoc comment to reference types from another module.

In your example, if you want to use the return type of the request function from src/a.js for the response parameter in the handleResponse function in src/b.js, you can do the following

src/a.js

/**
 * @returns {Promise<{name: string}>}
 */
export function request() {
  return Promise.resolve({
    name: "William",
  });
}

src/b.js

import { request } from './a';

/**
 * @param {ReturnType<typeof import('./a').request>} response
 * @returns {void}
 */
export function handleResponse(response) {}

Using import() in JSDoc comments allows you to reference types from other modules.

The syntax ReturnType<typeof import('./a').request> essentially translates to "the return type of the request function in the ./a module".

Comment if any more help required.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading