0

I was skimming through some documentation in the Angular docs and ran across this chunk of code:

return this.exampleDatabase!.getRepoIssues(
                this.sort.active, this.sort.direction, this.paginator.pageIndex);

Is this the TypeSrcript equivalent of the C# null-conditional operator for null checking?

I tried doing some stuff in JSFiddle but kept getting syntax errors:

Example:

const obj = { test: 'ing 123' };

console.log(obj.test);
console.log(obj!.doesntexist); // Excepting null here

But, instead, I get:

Uncaught SyntaxError: Unexpected token . at new Function () at exec (typescript.js:41) at HTMLDocument.runScripts (typescript.js:41)

mwilson
  • 12,295
  • 7
  • 55
  • 95
  • Duplicate of [In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?](https://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) – DrZoo Sep 05 '19 at 19:22

1 Answers1

4

That's the not-null-assertion operator. It basically tells typescript that the expression before it is not null and not undefined.

It's supposed to be used in cases where you as the developer are sure that a variable is defined but the compiler is unable to conclude that fact.


Looking into why this results in a syntax error on JSFiddle...

The transpiled code it's trying to run (using new Function(transpiled)()) contains this:

console.log(obj, !.doesntexist);

I couldn't find out what version of TypeScript they're using exactly, but it must be older than 2.0 when the operator was introduced.

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270