I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below.
enum DoSomething {
VALUE1,
VALUE2,
VALUE3,
}
function doSomething(doSomething?: DoSomething): void {
if (doSomething) {
console.log('do something')
} else {
console.log('do nothing')
}
}
doSomething(undefined) // -> do nothing
doSomething(DoSomething.VALUE1) // -> do nothing
doSomething(DoSomething.VALUE2) // -> do something
This issue arises because the VALUE1 of the enum is essentially 0. One solution could be to introduce a "NONE" value as the first position in the enum to avoid potential confusion with undefined values. What are your thoughts on this approach?
enum DoSomething {
NONE,
VALUE1,
VALUE2,
VALUE3,
}
function doSomething(doSomething: DoSomething): void {
if (doSomething) {
console.log('do something')
} else {
console.log('do nothing')
}
}
doSomething(DoSomething.NONE) // -> do nothing
doSomething(DoSomething.VALUE1) // -> do something
doSomething(DoSomething.VALUE2) // -> do something
While explicitly checking for undefined is always an option, overlooking the implications of if(0) can lead to debugging headaches, especially since it only fails for the first enum value. Any insights or suggestions on how to handle this scenario?