Skip to content
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

Merged
merged 6 commits into from
Jan 17, 2017

Conversation

ahejlsberg
Copy link
Member

@ahejlsberg ahejlsberg commented Jan 14, 2017

This PR improves our checking of nullable operands in expressions. Specifically, we now error in the following cases:

  • If either operand of a + operator is nullable, and neither operand is of type any or string.
  • If either operand of a -, *, **, /, %, <<, >>, >>>, &, |, or ^ operator is nullable.
  • If either operand of a <, >, <=, >=, or in operator is nullable.
  • If the right operand of an instanceof operator is nullable.
  • If the operand of a +, -, ~, ++, or -- unary operator is nullable.

An operand is considered nullable if the type of the operand is null or undefined or a union type that includes null or undefined. Note that the union type case only only occurs in --strictNullChecks mode because null and undefined disappear from unions in classic type checking mode.

Fixes #12795.

~~~~~~~~
!!! error TS2365: Operator '+' cannot be applied to types 'boolean' and 'boolean'.
~~~~
!!! error TS2531: Object is possibly 'null'.
Copy link
Member

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.

Copy link
Member Author

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants