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}"`)
}