Home > Software engineering >  What is the correct way to document a optional parameter of type boolean in JSDOC and WebStorm?
What is the correct way to document a optional parameter of type boolean in JSDOC and WebStorm?

Time:10-16

I've reviewed a few different Stack Overflow answers that got me to this point. So far I have tried the following.

    /**
     * Prints true, false or empty string
     * @param {boolean=} b
     */
    test = (b = '') => { // Initialized type string not assignable to variable type boolean
        console.log(`b = "${b}"`)
    }
    /**
     * Prints true, false or empty string
     * @param {boolean=} b
     */
    test = (b) => {
        // Initialized type string not assignable to variable type boolean
        if (typeof b !== 'boolean') b = ''
        console.log(`b = "${b}"`)
    }

I have a feeling the correct answer is suppress the warning, but hoping someone else has a better answer.

CodePudding user response:

In your code, the type can be either string or boolean, so you need using type union here:

/**
     * Prints true, false or empty string
     * @param {(boolean|string)=} b
     */
    test = (b) => {
        // Initialized type string not assignable to variable type boolean
        if (typeof b !== 'boolean') b = ''
        console.log(`b = "${b}"`)
    }

See https://jsdoc.app/tags-type.html

  • Related