if (node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
The !
operator after node.parent
caught my attention. What does it do?
Investigating the !
Operator
At first, I attempted to compile the file using my existing TypeScript version (1.5.3). This resulted in an error pointing directly to the exclamation mark:
$ tsc --noImplicitAny memberAccessRule.ts
noPublicModifierRule.ts(57,24): error TS1005: ')' expected.
Realizing it might be a newer feature, I upgraded to TypeScript 2.1.6. This time, the file compiled successfully without any issues. Interestingly, the TypeScript compiler completely ignored the !
when generating JavaScript:
if (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression) {
return;
}
What Does !
Do in TypeScript?
The !
operator is known as the non-null assertion operator. It tells TypeScript that a value is not null or undefined, overriding strict null checks. Essentially, it informs the compiler:
“Trust me,
node.parent
will always be defined here.”
Without !
, TypeScript might complain if node.parent
could be null
or undefined
. By adding node.parent!
, we assure the compiler that it’s safe to access .kind
without additional null checks.
When Should You Use !
?
While !
can be useful, it should be used carefully. If node.parent
is actually null
at runtime, it will result in a runtime error. It’s best to use !
only when you’re absolutely certain that a value will never be null
or undefined
. Otherwise, consider using optional chaining (?.
) or explicit null checks to handle potential null
values safely.