-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Noncrashing property access through non-null assertion operator should narrow that property to NonNullable #15655
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
Comments
this is behaving as intended. the |
|
The var x: number | string;
if (typeof (x as number).toFixed === "function") {
(x as number).toFixed(); // need to cast again
var y: number = x; // error, x is number | string
} |
@mhegazy what's our excuse for not unwrapping this, though? |
If we retrieved a property of an identifier, there's no reason to not consider that a truthiness guard of the same identifier. It's clearly not |
The assertion has no scope, it can appear in the middle of an expression, or in the middle of an if block, it is not clear what that means to the type for the rest of the block.. other narrowing constructs do have clear scoping semantics /control flow implications. We did discuss this before, but i can not find the issue at the moment. |
This isn't about applying the function test(bar: Bar) {
if (bar.foo!.optional) {
let num: number = bar.foo.optional; // Should not error!
} The dotted property access on |
related #9640 |
Well, it's actually about this: if (bar.foo!.optional) {
let num: number = bar.foo!.optional; // "Type 'number | undefined' is not assignable to type 'number'"
} although it was also surprising that I have to use |
If the For example, this: function test (a: { b?: { c: string } }) {
console.log(a.b!.c)
console.log(a.b.c)
} could be considered as being more-or-less equivalent to: function test (a: { b?: { c: string } }) {
if (a.b == null) throw new TypeError()
console.log(a.b.c)
console.log(a.b.c)
} as the second But the throw itself is done by the engine..... and is an expression throw... |
Has this ever been resolved? |
TypeScript Version: 2.3 (Playground)
Code
Using
strictNullChecks
.Expected behavior:
No errors or warnings.
Actual behavior:
num
in firstif
block isnumber | undefined
bar.foo
in firstif
block can beundefined
The text was updated successfully, but these errors were encountered: