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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With