Edit: I'm using TypeScript v2.2.1
I am new to TypeScript and I'm not sure what the cleanest way of dealing with DOM elements that may or may not exist is. Basically, I want to check whether an element exists, and then if it does, add an event listener to it (I have --strict_null_checks
turned on).
When I do it the JS-like way:
const myElement = document.getElementById('my-id');
if (myElement) {
myElement.addEventListener('click', (e:Event) => {
// Do stuff.
});
}
I get the error my_script.ts(3, 3): error TS2531: Object is possibly 'null'.
I can get around this by using a not-null assertion:
const maybeMyElement = document.getElementById('my-id');
if (maybeMyElement) {
const myElement = maybeMyElement!;
myElement.addEventListener('click', (e:Event) => {
// Do stuff.
});
}
But my understanding is that those sorts of assertions are generally frowned upon, and aesthetically, I don't like creating twice as many variables.
Is there a cleaner way to do this?
strictNullChecks
on). – Bridlewise