I wrote something like this the other day:
const element = document.querySelector('#aVerySpecifcElement');
element.addEventListener('click', doStuff);
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);
}
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);
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);
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:
Top comments (0)