Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reference a param type in JSDoc @return?

I would like to document a function whose return type depends on the supplied parameter:

/**
* @param {*} x A thing
* @return {????} The thing in an array
*/
function arrayOf(x) { return [x]; }

Is it possible to name or otherwise reference the actual type of the function param, so that I can use it to specify the return?

like image 445
Coderer Avatar asked Jul 25 '17 16:07

Coderer


People also ask

Does JSDoc support TypeScript?

You can use most JSDoc type syntax and any TypeScript syntax, from the most basic like string to the most advanced, like conditional types.

What is the JSDoc keyword to specify an argument to a function?

The @param tag provides the name, type, and description of a function parameter.

What does Param mean in JavaScript?

A parameter is a named variable passed into a function. Parameter variables are used to import arguments into functions. For example: function example(parameter) { console.

Why should I use JSDoc?

JsDoc is a great tool for documenting code and providing type-safety in your JavaScript project without any additional configuration. Learn what JsDoc is, how it works, the benefits it provides, and how to use it in your project.


2 Answers

I commented on the other answer that what I'm looking for boils down to a generic parameter, which is implemented in JSDoc with @template. I don't know if it's part of core JSDoc -- I think it's a Closure extension -- but Typescript does recognize it if you're running your JS through TS, or just trying to get autocomplete working in your IDE.

Adapted from that link:

/**
 * @template T
 * @param {T} x - A generic parameter that flows through to the return type
 * @return {T[]}
 */
function id(x) {
  return [x];
}
like image 192
Coderer Avatar answered Sep 21 '22 04:09

Coderer


Don't know if there is a generic way to represent - this needs to be specified within the function description, but following could be the options:

For an elaborate description, might create a thing typedef:

/**
 * Thing Type
 * @typedef {*} thing
 */

/**
 * Returns a single element array encapsulating only the param value
 * @param {thing} x A thing
 * @return {thing[]} The thing in an array
 */
function arrayOf(x) { return [x]; }

else, simply,

/**
 * Returns a single element array encapsulating only the param value
 * @param {*} x A thing
 * @return {*[]} The thing in an array
 */
function arrayOf(x) { return [x]; }
like image 27
overflower Avatar answered Sep 21 '22 04:09

overflower