21

I was looking through angular2 code and saw a few things such as:

this._outlets[name] = undefined !; 

What is the meaning of that ! at the end? Couldn't find anything on google about it :(

taigi100
  • 2,609
  • 4
  • 23
  • 42
  • 1
    Not sure what it means, although it's compiled to just `undefined` by TSC. Check [this sample](https://www.typescriptlang.org/play/#src=var%20test%20%3D%20undefined%20!%3B%20) – Leonardo Chaia Apr 28 '17 at 11:39
  • 4
    It tells the compiler that undefined is not undefined See http://stackoverflow.com/a/42274019/450611 – weirdan Apr 28 '17 at 11:40
  • Hey, that's cool @weirdan! – Leonardo Chaia Apr 28 '17 at 11:41
  • 1
    Possible duplicate of [In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?](http://stackoverflow.com/questions/42273853/in-typescript-what-is-the-exclamation-mark-bang-operator-when-dereferenci) – Igor Apr 28 '17 at 11:41
  • I'm still not sure what's the point in that particular example. Here's the code from [angular](https://github.com/angular/angular/blob/5293794316cc1b0f57d5d88b3fefdf6ae29d0d97/packages/router/src/router_outlet_map.ts#L28) – Leonardo Chaia Apr 28 '17 at 11:43
  • 1
    @LeonardoChaia Agree, makes sense and it's cool when you want to access some property but not yet sure what : `undefined is not undefined` means :) – taigi100 Apr 28 '17 at 11:45
  • The index signature defined for `_outlets` does not accept undefined values, you cannot assign `this._outlets[name] = undefined`. ` undefined !` fools the compiler into believing that `undefined is not undefined`, but at run-time `undefined` will be assigned to `this._outlets[name] ` – Saravana Apr 28 '17 at 12:46

2 Answers2

15

After some checking I found out that it is indeed telling the compiler that undefined is not undefined :)

In case you run the compiler with --strictNullChecks trying to assign undefined to something such as a string for example will yielf in the following error: Type "undefined" is not assignable to type "string". If you use undefined ! you basically bypass this check and tsc won't give you an error for it.

taigi100
  • 2,609
  • 4
  • 23
  • 42
4

This post-fix expression operator ! may be used to assert that its operand cannot be null or undefined during runtime.

karim somai
  • 129
  • 1
  • 3