简体   繁体   中英

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?

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

代码补全

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM