samanime
samanime

Reputation: 26615

Document JavaScript with optional first parameter

I'm trying to document one of those annoying functions which has an optional first parameter in JavaScript.

Something like the function .use() from express

function use(path, callback) // path is optional

I'm trying to find something that works, and ideally isn't terribly ugly.

My preference for the actual code signature would be this:

function use(...args) {
  const [callback, path] = args.reverse();
}

In that case, I don't have two parameters, so if I try to use two @param lines, I get yelled at in the JSDoc block:

/**
 * @param {String=} path
 * @param {Function} callback
 */
function use(...args) // mismatched parameters

If I use the parameters as intended and use a different pattern for putting the parameters in place, I get yelled at (by WebStorm) because callback isn't a String:

/**
 * @param {String=} path
 * @param {Function} callback
 */
function use(path, callback) {
  if (typeof path == 'function') {
    callback = path; // yelled at because callback can't be a string
    path = undefined;
  }
}

I've googled around and found lots of older stuff with different people debating this problem, but no clear answers. Since the posts are older and a lot has happened, I wanted to ask anew: Is there a way to document this so everything is happy (at least in WebStorm), or is there some new ES# syntax that allows for optional first parameters (that can generate proper auto-complete)?

Upvotes: 2

Views: 148

Answers (1)

vzwick
vzwick

Reputation: 11054

@param {(String=|Function=)} path

is probably what you are looking for.

Upvotes: 1

Related Questions