Suggestion: --noImplicitBooleanConversion #9702
Labels
Out of Scope
This idea sits outside of the TypeScript language design constraints
Suggestion
An idea for TypeScript
Typescript forbids automatic conversion to boolean in function calls, which makes sense, since there's actually no coercion in the generated typescript code when passing a non-boolean argument to a function taking a boolean. The Javascript function would receive a non-boolean.
However, it allows coercion to boolean in 'if', 'while', 'for' and 'operator !'
This can lead to hard-to-find bugs, such as:
Proposal
Reduce the likelihood of such bugs, by adding a flag --noImplicitBooleanConversion that will make the following expressions illegal:
when a has the type 'number | undefined' or 'string | undefined' (and possibly more involving 'null' or combinations of 'number' and 'string')
I also suggest that in this case, the coercion can be forced with:
which are then legal.
Coercion to boolean of variables where the type is just 'number' or 'string' would always remain legal.
Further discussion
The above only addresses one very common pattern, and doesn't address the expression !a outside of the if context. Finding a suitable "override" syntax might be challenging (the equivalent of if! for the above case).
It also doesn't address expressions like 'a && f(a)', 'a || 5' or '(a ? a : 5)', which might also produce unexpected results when a is of type 'number | undefined'. These could be explored.
The text was updated successfully, but these errors were encountered: