DEV Community

Andreas Riedmüller
Andreas Riedmüller

Posted on • Edited on

The Non-null Assertion Operator (!) in TypeScript

Let’s face it—TypeScript’s type safety is amazing, but there are times when you know more about your code than TypeScript does. One situation that comes up a lot is when TypeScript insists that a value might be null or undefined, even though you're 100% sure it's not. This is where the Non-null Assertion Operator ! comes into play.

Below is a simple code snippet demonstrating when this operator is unnecessary. TypeScript infers that video in the log statement is not null:

if (state.video !== null) {
  console.log(state.video.title); // TypeScript is happy.
}
Enter fullscreen mode Exit fullscreen mode

But if you’re working with more complex conditions, for example updating nested properties in a produce call (for those who love immer!), TypeScript might not infer everything perfectly. It’ll think, “What if video suddenly becomes null?” To solve this, you use a type assertion:

if (state.video !== null) {
  const updatedState = produce(state, (draftState) => {
    draftState.video.title = "Hello Video!"; // TypeScript complains: 'draftState.video' is possibly 'null'.ts(18047)
  });
}

if (state.video !== null) {
  const updatedState = produce(state, (draftState) => {
    draftState.video!.title = "Hello Video!"; // TypeScript is happy again :-)
  });
}

Enter fullscreen mode Exit fullscreen mode

That ! is saying to TypeScript: “I know what I’m doing. Trust me, this value is not null or undefined.” It’s a little trick to bypass TypeScript's complaints when you know it’s safe.

To be clear, I’m not saying you should sprinkle ! everywhere. If you use it carelessly, you might end up with bugs because you bypassed TypeScript’s safety net. But when you know your logic is solid, it’s a great tool to have.

For example, when working with APIs, TypeScript might not always infer the structure exactly as you need, especially with libraries that don’t have the strongest types. Instead of wasting time creating elaborate type guards or refactoring everything, you can assert certain fields as non-null using !.

I use this sparingly, but if the situation requires it, ! saves me time and unnecessary additional checks in the code.

Top comments (0)