Improved checking of nullable operands in expressions#13483
Improved checking of nullable operands in expressions#13483ahejlsberg merged 6 commits intomasterfrom
Conversation
| ~~~~~~~~ | ||
| !!! error TS2365: Operator '+' cannot be applied to types 'boolean' and 'boolean'. | ||
| ~~~~ | ||
| !!! error TS2531: Object is possibly 'null'. |
There was a problem hiding this comment.
Object is definitely null, and typically we don't think of objects as being operands to arithmetic operations (whereas we do when it comes to primitives). Would be nice if we could be more precise on the error message.
There was a problem hiding this comment.
Two orthogonal issues:
First, we could do extra work to omit the word possibly when the type is exactly null or undefined. However, it is very rare for someone to explicitly use null or undefined as an operand, so it's not clear that it really matters all that much. This is the type of error that only surfaces in a test.
Second, we could consider using the word value instead of object when reporting for expression operands--but it's really the same error that we use for obj.foo where obj may be null or undefined. The downside would be error message searchability, but since the error is pretty obvious that may not be an issue.
This PR improves our checking of nullable operands in expressions. Specifically, we now error in the following cases:
+operator is nullable, and neither operand is of typeanyorstring.-,*,**,/,%,<<,>>,>>>,&,|, or^operator is nullable.<,>,<=,>=, orinoperator is nullable.instanceofoperator is nullable.+,-,~,++, or--unary operator is nullable.An operand is considered nullable if the type of the operand is
nullorundefinedor a union type that includesnullorundefined. Note that the union type case only only occurs in--strictNullChecksmode becausenullandundefineddisappear from unions in classic type checking mode.Fixes #12795.