In Typescript, that is! (exclamation point / explosion) when dereferencing a member?

Looking at the source code for the tslint rule, I came across the following statement:

if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) { return; } 

Pay attention to the operator ! after node.parent . Interesting!

At first I tried to compile the file locally with my installed version of TS (1.5.3). The error received indicated the exact location of the explosion:

 $ tsc --noImplicitAny memberAccessRule.ts noPublicModifierRule.ts(57,24): error TS1005: ')' expected. 

Then I upgraded to the latest version of TS (2.1.6), which compiled it without any problems. So this seems to be a feature of TS 2.x. But the transpilation completely ignored the hit, resulting in the following JS:

 if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) { return; } 

My google fu still failed me.

What is the TS exclamation mark operator and how does it work?

+312
typescript tslint
Feb 16 '17 at 12:22
source share
2 answers

This is a nonempty statement statement. This is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility that it is null or undefined ." Sometimes the type checker cannot perform this determination on its own.

It explains :

New post-fix expression statement ! can be used to assert that its operand is not null and not undefined in contexts where the type checker cannot complete this fact. In particular, the operation x! returns a value of type x with null and undefined excluded. Like statements like the forms <T>x and x as T , the operator ! non-null asserting is simply removed in the emitted JavaScript code.

I believe that the use of the term “affirm” is a little misleading in this explanation. This is a "statement" in the sense that the developer claims it, and not in the sense that the test will be completed. The last line does indicate that this does not emit JavaScript code.

+471
Feb 16 '17 at 12:29
source share

Louis's answer is wonderful, but I thought I'd try to summarize briefly:

The bang statement tells the compiler to temporarily relax the non-null constraint that might otherwise be required. He tells the compiler: "As a developer, I know better than you that this variable cannot be null right now."

+100
May 10 '17 at 11:32
source share



All Articles