In Typescript, when assigning a default value to a parameter of type string, the empty string counts as something and the default value is not used.
This makes sense, but in some cases, I'd like to change that:
function greet (name?: string = 'visitor') {
console.log(`Hello ${name}`)
}
greet('Gromit') // logs "Hello Gromit"
greet() // logs "Hello visitor"
greet('') // logs "Hello " <--- How can I get the default value in this case too?
Does Typescript perhaps have a feature, which I am not finding, to help define when I want the default value to apply?
I have been using what I consider to be a workaround, for now:
const defaultName = 'visitor'
function greet (name?: string = defaultName) {
const finalName = name || defaultName
console.log(`Hello ${finalName}`)
}
But I would rather use something cleaner and more idiomatic to Typescript and I would be surprised if a better pattern doesn't exist.
To be clear, I would have expected to find a way to do this within that part of the code responsible for defining the function parameters:
function greet (/* here */) {}
The proposed solutions introduce code outside of this section the same as I do in my workaround.
Thanks for any pointers!