-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Improved checking of nullable operands in expressions #13483
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.