-
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
Proposal: Error when using non-null assertion on already non-null expression #13784
Comments
I can see this as one of those checks that would sometimes be useful but at other times create unnecessary issues, say, when a variable's type is changed from a nullable to a non-nullable and back again to a nullable (when the type is inferred, this can happen in a very different part of the code). As you mentioned, if applied to types inferred through flow analysis it could make this a "programming annoyance" in some cases (like the way Go effectively tortures the programmer to remove package imports whenever they become unused and add them back when they are needed, over and over again). I guess it can technically be covered by a type-checked |
See #8453 |
@RyanCavanaugh from what I see in the linked discussion, it was only about superflous non-null warnings. This issue also discusses introducing a warning when Would a PR implementing the superflous warning, but preferring declared types so the described annoying case doesn't happen be considered for merge? |
I'm not sure which behavior you're referring to here. Can you show an example? |
I described it in the original post, perhaps not clearly enough. The naïve implementation I did provides an error for the following code: let x: string | undefined | null;
x = "";
x!.indexOf("foo"); // Error provided here, because type has been narrowed to just `string` If instead we made it only consider--if present--the declared type of variables, the above code wouldn't error. There's technically nothing wrong with providing the error using the control flow narrowed type, but judging from the original discussion in the linked issue, it seems like this is a concern. |
Original idea from this stack overflow post.
Code
Wanted behavior:
A compiler error or warning about superflous use of the non-null assertion operator
!
.Actual behavior:
No compiler warnings or errors.
Implementation details
Naive implementation using the current control-flow assigned type can be found here.
It poses a problem on code like the following:
Whether control-flow type narrowing should affect the error or the analysis should prefer declared types is a point of discussion.
As a corollary, I also made using the operator an error when not compiling with
strictNullChecks
, but this produces errors when compiling the ts codebase itself.Language feature checklist
The text was updated successfully, but these errors were encountered: