Noncrashing property access through non-null assertion operator should narrow that property to NonNullable
See original GitHub issueTypeScript Version: 2.3 (Playground)
Code
Using strictNullChecks
.
interface Foo {
optional?: number;
}
interface Bar {
foo?: Foo;
}
function test(bar: Bar) {
if (bar.foo!.optional) {
let num: number = bar.foo.optional;
}
if (bar.foo && bar.foo.optional) {
let num: number = bar.foo.optional;
}
}
Expected behavior: No errors or warnings.
Actual behavior:
num
in firstif
block isnumber | undefined
bar.foo
in firstif
block can beundefined
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:11 (7 by maintainers)
Top Results From Across the Web
Noncrashing property access through non-null assertion ...
Noncrashing property access through non-null assertion operator should narrow that property to NonNullable #15655.
Read more >TypeScript non-null assertion operator does not work
I have a type with a conditional property (in this case 'b') type tp1 = {a: string, b?: Array<number>};. I create an object...
Read more >Using the non-null assertion operator - Learn TypeScript
Using the non-null assertion operator. In this lesson, we will learn how the non-null assertion operator can narrow a type.
Read more >A note on TypeScript non-null assertion operator - Medium
It lets you deliberately ignore an expression's possible null -ness on a case-by-case basis.
Read more >Documentation - TypeScript 2.0
A property access or a function call produces a compile-time error if the object or ... the ! non-null assertion operator is simply...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
If the
!
operator is used before a.
or()
, it could be considered a narrowing operator.For example, this:
could be considered as being more-or-less equivalent to:
as the second
a.b.c
is not reachable ifa.b!.c
’s erasure ofnull|undefined
does not happen to be proved true at runtime.But the throw itself is done by the engine… and is an expression throw…
This isn’t about applying the
!
operator to the rest of the block. It’s about this:The dotted property access on
bar.foo
should act as an equivalent type guard toif (bar.foo) {
, because the fact we got inside theif
block without crashing means it’s notnull
/undefined