DEV Community

ginger
ginger

Posted on • Originally published at ginger.wtf

The super power that lets you tell TypeScript what is actually happening

I wrote something like this the other day:

const element = document.querySelector('#aVerySpecifcElement');

element.addEventListener('click', doStuff);
Enter fullscreen mode Exit fullscreen mode

But this wasn't enough for TypeScript. Why? Because when querySelector doesn't find anything, it returns null. That's not Element.

My brain immediately went to fixing it like this:

const element = document.querySelector('#aVerySpecificElement');

if (!!element) {
    element.addEventListener('click', doStuff);
}
Enter fullscreen mode Exit fullscreen mode

You can also use the optional chaining operator ?. to do something similar.

const element = document.querySelector('#aVerySpecificElement');

// if nullish, don't do the next thing
element?.addEventListener('click', doStuff);
Enter fullscreen mode Exit fullscreen mode

But this is caving. This is admitting defeat.

So what gives?

In comes the ! operator. Fun fact, did you know in a time gone by, the ! exclamation mark was called a "bang".

The bang ! operator is like the optional chain, but it tells TypeScript "Actually, I know for A FACT that this is not going to be null or undefined."

const element = document.querySelector('#aVerySpecificElement');

element!.addEventListener('click', doStuff);
Enter fullscreen mode Exit fullscreen mode

No longer do we need to add unnecessary if statements just to appease a compiler.

What if it actually can be undefined?

Then don't use it silly!

If you are asking that question, then don't worry about using it. Let TypeScript whisk your worries away. Then when you're pulling your hair out trying to write a type guard to account for the possibility of null, give it a shot.

References:

The release notes for TypeScript 2.0

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay