-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Improved checking of nullable operands in expressions #13483
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 typeany
orstring
.-
,*
,**
,/
,%
,<<
,>>
,>>>
,&
,|
, or^
operator is nullable.<
,>
,<=
,>=
, orin
operator is nullable.instanceof
operator is nullable.+
,-
,~
,++
, or--
unary operator is nullable.An operand is considered nullable if the type of the operand is
null
orundefined
or a union type that includesnull
orundefined
. Note that the union type case only only occurs in--strictNullChecks
mode becausenull
andundefined
disappear from unions in classic type checking mode.Fixes #12795.