Michael Hobbs
Michael Hobbs

Reputation: 1693

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

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.

Upvotes: 0

Views: 2184

Answers (1)

lena
lena

Reputation: 93868

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

Upvotes: 2

Related Questions