DEV Community

hesxenon
hesxenon

Posted on

the (not so big) Bang!

Premise

So I've just read this article here in which the author basically throws typescripts warning regarding potentially undefined values into the wind with the bang operator.

In short this allows you to do something like this:

const maybeElement = document.getElementById("foo");
maybeElement!.addEventListener(...); // <-- notice the ! before the .
Enter fullscreen mode Exit fullscreen mode

So with this we can tell typescript to ignore the problems of accessing a property on a potentially null value.

My initial thoughts on this were "yeah, and if you'd use that in my codebase without a comment we'd have a stern talk" and while I stand by that - at least put a comment there on why you're sure it's not nullish - there is something to be said in favor of telling typescript to shut up; especially in a case like hers.

The Problem

So lets assume we don't want to do this and we just use the elvis operator (?.) instead -> maybeElement?.addEventListener. Great, now our code doesn't crash when the element isn't defined.

But think again... in such a scenario, what would be easier to trace? If the id of the element changes, maybeElement becomes null and with the bang operator it crashes "loudly" a few lines below.

If we just mindlessly change the ! into a ? it doesn't crash - but the event listener also isn't added which in turn means that we probably have a far more intricate and difficult to track bug on our hands. Maybe that bug even isn't discovered for a day or two and then what? Are you confident enough that you'll find the mistake within the same amount of time and effort as when the ! was still there?

The solution

Be mindful about your operators. It's not like ?. has no drawbacks and failing early is typically better. If you want to express "I need this to be non nullish" using ! could be acceptable - of course the best solution here would be to take a step back and think about what to do in case the element isn't found, which is why typescript warns you in the first place.

Conclusion

  • no such thing as mindless programming
  • ?. can easily be abused to delay surfacing of errors
  • using ! probably means you should think harder about proper errors. Maybe an either/result monad as encapsulated by various libraries like fp-ts and effect?

Top comments (0)