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.
// 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) {}
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.