1265

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
Mike Chamberlain
  • 39,692
  • 27
  • 110
  • 158
  • You have a lazy developer in your team ^^; Your IDE would give you an error message if there is no type definition, or the prop may be undefined in runtime. `!` will bypass this error message, which is something like: "I tell you, it will be there." –  Jul 09 '22 at 11:15

6 Answers6

1765

That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here, so don't complain about the possibility of it being null or undefined." Sometimes the type checker is unable to make that determination itself.

It is explained in the TypeScript release notes:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.

Pang
  • 9,564
  • 146
  • 81
  • 122
Louis
  • 146,715
  • 28
  • 274
  • 320
  • 31
    Good explanation. I find it a good practice to do a `console.assert()` on the variable in question before appending a `!` after it. Because add `!` is telling the compiler to ignore the null check, it compiles to noop in javascript. So if you are not sure that the variable is non-null, then better do an explicit assert check. – Jayesh Aug 28 '17 at 19:35
  • 76
    As a motivating example: using the new ES Map type with code like `dict.has(key) ? dict.get(key) : 'default';` the TS compiler can't infer that the `get` call never returns null/undefined. `dict.has(key) ? dict.get(key)! : 'default';` narrows the type correctly. – kitsu.eb May 30 '18 at 22:58
  • 7
    Is there slang for this operator, like how the Elvis operator refers to the binary operator? – ebakunin Jan 09 '20 at 20:40
  • @Jayesh could you expand on the console.assert() good practice, could you post an example? – Christopher Francisco Mar 16 '20 at 19:40
  • 9
    @ebakunin "The bang operator", as you can see below in Mike's answer – Serhii Apr 30 '20 at 09:06
  • 4
    @ebakunin, Elvis `?.` AFAIK came from the C# land. With nullable types, [C# got its bang too](https://docs.microsoft.com/dotnet/csharp/language-reference/operators/null-forgiving) (pun, of course, intended). Yup, the Sir Tony's invention wroke a serious havoc on the world of procedural programming, and we still cleaning the fallout. Being the sweetest person, he still apologizes for it. Curiously, his major contribs to CS are in automatic reasoning about program correctness (e.g., Hoare logic), applied in static code analysis: he invented both the null and the ways to statically catch it! :) – kkm inactive - support strike Aug 11 '20 at 10:04
  • 1
    I thought ?: was the Elvis operator. ?. is the safe navigation operator? – Charles Robertson Jan 10 '22 at 23:51
  • 3
    I call it the "trust me bro operator" – Creative Jan 04 '23 at 09:40
  • Oh, so they should call it the "trust me" operator. – James M. Lay Aug 08 '23 at 17:07
418

Louis' answer is great, but I thought I would try to sum it up succinctly:

The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".

Mike Chamberlain
  • 39,692
  • 27
  • 110
  • 158
  • 15
    Or, as the compiler, it has messed up. If the constructor does not initialize a property but a lifecycle hook does it and the compiler does not recognize this. – Mukus Jun 26 '18 at 23:50
  • 47
    This is not the responsibility of the TS compiler. Unlike some other languages (eg. C#), JS (and therefore TS) does not demand that variables are initialized before use. Or, to look at it another way, in JS all variables declared with `var` or `let` are implicitly initialized to `undefined`. Further, class instance properties can be declared as such, so `class C { constructor() { this.myVar = undefined; } }` is perfectly legal. Finally, lifecycle hooks are framework dependent; for instance Angular and React implement them differently. So the TS compiler cannot be expected to reason about them. – Mike Chamberlain Jul 03 '18 at 14:22
  • 1
    Is there a valid use case for the bang operator considering the awesomness of control flow based type analysis in TS? – Eugene Karataev Apr 22 '20 at 16:24
  • 4
    @EugeneKarataev Yes there is, frameworks often initialize variables inside themselves and the ts control flow analysis can’t catch it. It’s usage is certainly reduced, but you will come across instances where you need it. – arg20 May 04 '20 at 16:03
  • 2
    @arg20 let's say variable `foo` was initialized by a framework. What are the benefits of `foo!.bar` compared to `foo?.bar`? I see only a disadvantage: `!` operator might throw in runtime while optional chaining will not. – Eugene Karataev May 04 '20 at 16:56
  • 7
    @EugeneKarataev readability for one thing. The exclamation sign tells the reader of the code: THIS CANNOT BE NULL. (sorry about caps). While `?` says: this might be `null`, which is not true (therefore you can only use `!` if you ABSOLUTELY know it's not `null`. – arg20 May 05 '20 at 18:54
  • 9
    @EugeneKarataev the difference is that `?.` return type is nullable (even if it can't ever happen), and you'll have to deal with a nullable type down the road. While if you know null is impossible, `!.` fixes the type once and for all. – Emile Bergeron Sep 23 '20 at 17:57
  • 2
    "As a developer I understand that this code may cause errors at run time and that is my desire" – thepaulpage Jan 29 '21 at 04:35
  • "As the developer, I dare you to touch my nulls!!!" – Shadi Alnamrouti Jan 31 '21 at 12:30
  • 1
    After not QUITE being sure I was understanding correctly, @thepaulpage's answer helped solidify it. Ty. – BBaysinger Mar 17 '21 at 05:42
  • @MikeChamberlain a small correction: `let` is not initialized with `undefined`, only `var` is :-) – decebal Mar 03 '22 at 15:31
90

Non-null assertion operator

With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null or undefined. This is can be useful when the compiler cannot infer the type with certainty but we have more information than the compiler.

Example

TS code

function simpleExample(nullableArg: number | undefined | null) {
   const normal: number = nullableArg; 
    //   Compile err: 
    //   Type 'number | null | undefined' is not assignable to type 'number'.
    //   Type 'undefined' is not assignable to type 'number'.(2322)

   const operatorApplied: number = nullableArg!; 
    // compiles fine because we tell compiler that null | undefined are excluded 
}

Compiled JS code

Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature

"use strict";
function simpleExample(nullableArg) {
    const normal = nullableArg;
    const operatorApplied = nullableArg;
}
Sumit
  • 2,242
  • 1
  • 24
  • 37
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
40

Short Answer

Non-null assertion operator (!) helps the compiler that I'm sure this variable is not a null or undefined variable.

let obj: { field: SampleType } | null | undefined;

... // some code

// the type of sampleVar is SampleType
let sampleVar = obj!.field; // we tell compiler we are sure obj is not null & not undefined so the type of sampleVar is SampleType
Masih Jahangiri
  • 9,489
  • 3
  • 45
  • 51
3

My understanding is the ! operator do the same thing like NonNullable.

let ns: string | null = ''
//  ^? let ns: string | null
let s1 = ns!
//  ^? let s1: string
let s2 = ns as NonNullable<typeof ns>
//  ^? let s2: string
hfutsora
  • 91
  • 4
0

Non-Nullable TypeScript performs strict null checks to help catch potential null or undefined errors. When you try to access a member (property or method) on a variable that could be null or undefined, TypeScript raises a compilation error.

let myElement: HTMLElement | null = document.getElementById('myElement');

// Without non-null assertion operator
// Compiler error: Object is possibly 'null'.
myElement.innerHTML = 'Hello, world!';

// With non-null assertion operator
myElement!.innerHTML = 'Hello, world!';