Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.2Selecting and typing DOM elements

Selecting elements

DOM selectors may fail, so TypeScript correctly includes null in their result. Check first instead of using a type assertion to silence the warning.

TypeScript
const button = document.querySelector<HTMLButtonElement>("#save");

if (button) {
  button.disabled = true;
}

Handling null

The check is not ceremony: it records that an absent element is expected and dealt with. If an element is genuinely required, throw a helpful error close to the selector rather than using ! throughout the codebase.

Feedback 👍
Comments are sent via email to me.