Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSDoc: How to document an object with mix of dynamic and fixed properties?

Suppose I have a function like so:

function validator(obj){
  const ret = {};

  for (const key in obj){
    // Returns a boolean
    result = validate(key, obj[key]);

    if (result !== true)
      ret.error = true;

    ret[key] = result;
  }

  return ret;
}

This function will return an object, the content of the object is dynamically populated depending on the argument passed to the function.

I can document the function like so:

/**
 * @param {Object.<string, *>} obj
 * @returns {Object.<string, boolean>}
 */

But it doesn't document the dynamic .error property that will also return a boolean.

If it is all it will return, I can simply write:

/**
 * @param {Object.<string, *>} obj
 * @returns {{error: boolean}}
 */

But then it doesn't document the dynamic properties now.

What I can think of doing is something like:

/**
 * @param {Object.<string, *>} obj
 * @returns {Object.<string, boolean>|{error: boolean}}
 */

While it works, it doesn't look syntactically correct to me. I can't use @typedef because it should be used when I already know what property will be used.

I can't find anything regarding this issue in the JSDoc's documentation.

So how do I document an object with mix of dynamic and fixed properties?

like image 778
yqlim Avatar asked May 06 '19 07:05

yqlim


1 Answers

You can do this with a template

/**
 * @template {Object<string,any>} T
 * @param {T} obj
 */
function validator(obj){
    /** @type {T & {error?: Boolean}} */
    const ret = {};
  
    for (const key in obj){
      // Returns a boolean
      const result = validate(key, obj[key]);
  
      if (result !== true)
        ret.error = true;
  
      ret[key] = result;
    }
  
    return ret;
  }

Example of code completion

Code completion

like image 174
JakeDK Avatar answered Oct 26 '22 04:10

JakeDK