I had a bug today where I unexpectedly skip a call to a function because my variable was 0:
const foo: number | undefined = getFoo();
if(foo) {
// Will not be called if foo is zero
doSomething(foo);
}
This is a pattern I use pretty often, testing if a variable is defined. This works with everything, objects, arrays, strings... Except number.
This is not the 1st time I got a bug like this.
Is there a rule that will alert me, something like:
if(foo)
--- Warning, testing a number variable that can be defined, but equals to zero
Something that will force me to write:
if(foo !== undefined)
It is less pretty, but at least it has the correct behaviour.
Edit: after thinking about this, it appears that the same problem can occur with the type string and the value "" (empty string)