javascriptnode.jsjsdoccode-documentation

JSDoc function returning a parameter of itself


I need to document a function returning conditionally one of its parameters. But JSDoc seems not to accept variables as a return value.

I tried to do something like this following the return type {1 | 0} logic

/**
 * Finds the page with given index and returns
 *  - index if it does not exist
 *  - user if user doesn't have permissions to read
 *  - else the page itself 
 * 
 * @param {number} index 
 * @param {string} user 
 * @returns {index|user|Page}
 */
function getRead(index, user) {
    let page = pages.find(page => page.details.index == index);
    if (page && page.canRead(user)) {
        return page;
    } else if (!page) return index;
    else return user;
}

But it is not recognized and the return values is just any, if i use {string|number|Page} as type, afterwards in my code I do something like this

if(page == index) return res.send(`Page ${index} does not exist`);
if(page == user) return res.send(`No permissions to view page ${index}`);
//page still recognized as number | string | Page
//no code completion or property suggestions on page

I also tried to add type checks to get there but i don't want to believe that like such a lazy the solution is the only one, there must be a better way to handle this

if(typeof page == "number" || page == index) return res.send(`Page ${index} does not exist`);
if(typeof page == "string" || page == user) return res.send(`No permissions to view page ${index}`);
//page recognized as Page

Solution

  • There are several solutions:

    1. Use generic types for parameters
    /**
     * Finds the page with given index and returns
     *  - index if it does not exist
     *  - user if user doesn't have permissions to read
     *  - else the page itself 
     * 
     * @template {number} IndexType
     * @template {string} UserType
     * @param {IndexType} index 
     * @param {UserType} user 
     * @returns {IndexType|UserType|Page}
     */
    function getRead(index, user) {
     ...
    }
    

    enter image description here

    1. Remove JSDoc for the function at all and rely on TypeScript's type inference
    function getRead(/**@type {number}*/index, /**@type {string}*/user) {
      ...
    }
    

    enter image description here