-
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
"Object is possibly null" After Non-Null Assertion #37798
Comments
I guess you meant to use the optional chaining here? https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining const obj: { a: number } | null = Math.random() > .5? null : { a: 42 };
if (obj?.a) {
console.log(obj.a);
} |
@nicojs No. I mean non-null assertion. I know that works with optional chaining operator, but that's not the case. It should produce no errors even with non-null assertion, since we let the compiler know (at line 3) that |
I'm pretty sure the non-null assertion operator works as intended here. With non-null assertion you're effectively saying to TypeScript "I know it might be nullish, but I know better, please let me use it this one time". It doesn't interfere with control flow analysis. Although this is not explicitly found in the handbook: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator. Maybe adding this small example could help with that? |
@nicojs What's the point? If |
See #9640 In general we don't do "if it didn't crash" reasoning since it's very difficult to fit into an efficient control flow analysis, which is really what you're asking for since the same reasoning would apply to this example: const obj: { a: number } | null = null;
if (obj!.a) {
}
console.log(obj.a); |
TypeScript Version: 3.7.x-dev.201xxxxx
Search Terms:
typescript object is possibly null after non null assertion
typescript object is possibly null after exclamation mark check
Code
Expected behavior:
Successful compilation, since we notify the compiler with non-null assertion at line 3 that
obj
is notnull
, then it's notnull
at line 4 too.Actual behavior:
Error "Object is possibly null" at line 4 (
console.log(obj.a)
).Playground Link: https://www.typescriptlang.org/play?ts=3.9.0-dev.20200328#code/MYewdgzgLgBCBGArAXDA3jAhqsBXAtvAKYBOMAvjAD4x4A2dMAvLbgwNwBQnAlgGYwAFAkQBCAHSYAlOk4x5MUJBB0i4uiADmwpJKldycmEA
Related Issues:
The text was updated successfully, but these errors were encountered: