Sikau

TypeScript · Day 22 · about 30 min

Typing the DOM

Elements, null checks and events.

The browser, typed

TypeScript knows every HTML element and event: an input has .value, a click has .clientX. It also knows querySelector might find nothing. Typed DOM code catches "null" crashes and typos in property names.

Element types

const input = document.querySelector<HTMLInputElement>("#name");
const out = document.querySelector("#out");

input?.addEventListener("input", (event) => {
  const target = event.currentTarget as HTMLInputElement;
  if (out) out.textContent = "Hello, " + target.value;
});

The rest of this lesson

  • Element types and eventsexplain
  • Null checks, not assertionsexplain
  • Will it type-check?predict
  • Inferred element typepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript