It seems like you don't have any idea what you are doing
[Edited] In TypeScript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
asked 1 year agoAsked
2Answers
110Views
Edited!
When looking at the source code for a tslint rule, I came across the following statement:
if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
Notice the !
operator after node.parent
. Interesting!
I first tried compiling the file locally with my currently installed version of TS (1.5.3). The resulting error pointed to the exact location of the bang:
$ tsc --noImplicitAny memberAccessRule.ts
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.
Next, I upgraded to the latest TS (2.1.6), which compiled it without issue. So it seems to be a feature of TS 2.x. But, the transpilation ignored the bang completely, resulting in the following JS:
if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
My Google fu has thus far failed me.
What is TS's exclamation mark operator, and how does it work?
2 Answers
The !
operator is used after node.parent
to assert that node.parent
is not null or undefined. This is useful when you are certain that the variable is not null at that point in the code, but the compiler is unable to infer it due to the structure of the code.
Write your answer here
Made with by Haseeb Yousuf