Boolean() cannot be used to perform a null check
See original GitHub issueTypeScript Version: 2.4.0
Apologies for today’s issue raising binge.
Code
// Compiles
const nullCheckOne = (value?: number) => {
if (!!value) {
return value.toFixed(0);
}
return '';
}
const nullCheckTwo = (value?: number) => {
if (Boolean(value)) {
// Object is possibly 'undefined'
return value.toFixed(0);
}
return '';
}
Expected behavior: Both examples compile.
Actual behavior:
The latter example fails w/ Object is possibly 'undefined'
.
Explanation
To my knowledge !!value
and Boolean(value)
are equivalent. I’m wondering what is the reason behind not supporting the second case. One reason I can think of would be an imported, non-typescript module, globally overriding it to something like: Boolean = (value) => !value
.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:41
- Comments:18 (7 by maintainers)
Top Results From Across the Web
Java check if boolean is null - Stack Overflow
boolean is a primitive type, and therefore can not be null. Its boxed type, Boolean ...
Read more >Avoid Null Booleans in Java. Do you prefer boxed primitives?
A null Boolean means that the variable has no reference assigned, so it is neither true nor false, it is “nothing”. What can...
Read more >Use == instead of ?: when dealing with nullable boolean
Why you should care ... Nullable boolean can be null, or having a value “true” or “false”. ... Before accessing the value, we...
Read more >New rule suggestion: "Boolean" objects should be used in a ...
This causes bugs which are really difficult to see in merge request reviews (because mostly you think of a boolean value which can't...
Read more >Bug descriptions — spotbugs 4.7.3 documentation
A method that returns either Boolean.TRUE, Boolean.FALSE or null is an accident waiting to happen. This method can be invoked as though it...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
One common pattern using the boolean constructor is
.filter(Boolean)
to remove falsy values from an array (includingnull
andundefined
).For anyone else running into the specific case of
Array.filter(Boolean)
, adding an overload forArray.prototype.filter()
works great. I’ve tested this on 4.1.2 and https://github.com/microsoft/TypeScript/issues/31551#issuecomment-495201128 doesn’t seem to be present anymore. PatchingBoolean
itself should work too, but I haven’t tried that.