Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 96 ยท Projects

Project: Type-Safe DOM Widgets

Build three typed browser widgets in TypeScript - a counter, a show/hide password toggle and a drag-and-drop list - with testable logic and DOM-shaped interfaces.

Small interactive widgets are where most people first write TypeScript for the browser: a quantity counter on a product page, an eye icon that shows a password, a list you can reorder by dragging. They look simple, and that's exactly why they collect bugs: an element that isn't on the page, a button that stays enabled past the maximum, a drag that drops into the wrong place, a widget that keyboard users can't operate at all.

In this project you'll build all three widgets with one design rule: keep the logic separate from the DOM. Each widget is a pure core (functions that take values and return values) plus a thin layer that talks to elements through a small interface describing only what the widget needs. Real DOM elements fit those interfaces, so the same code runs in the browser. Small fake objects fit them too, so you can run and test the widgets anywhere, including our editor.

Our editor runs TypeScript on Node.js without the DOM library, so document, HTMLElement and friends don't exist there (see TypeScript and the DOM). The runnable stages use hand-written, DOM-shaped interfaces and fake elements. At the end you'll find the complete browser code, read-only, which wires the same widgets to real elements. It was type-checked against the real DOM types.

The plan

Stage Widget Main TypeScript ideas
1 Counter with min, max and step Narrow interfaces, literal union actions, exhaustive switch, getters
2 Show/hide password Narrower-than-DOM types, typed attribute names, a returned control object
3 Drag-and-drop list with keyboard support Discriminated union events, generic helpers, never checks
4 The real browser code instanceof narrowing, adapters, DragEvent and KeyboardEvent

Why DOM-shaped interfaces?

A function that takes an HTMLButtonElement can only be called with a real button, which means you need a browser (or a heavy fake DOM) to run it. But a counter doesn't use 300 properties of a button. It uses two: disabled and addEventListener('click', โ€ฆ). If the parameter's type says exactly that, three things get better:

  • The dependency is documented. Reading interface ButtonLike { disabled: boolean; addEventListener(...) } tells you everything the widget touches.
  • Testing is trivial. Any object with those two members works, so a tiny class stands in for a button in tests.
  • Real elements still fit. TypeScript's type system is structural: an HTMLButtonElement has disabled and a compatible addEventListener, so you pass it in directly, no wrapper needed.

This is the same idea as programming against interfaces in a back-end service, applied to the DOM.

Stage 1: a counter

The counter shows a number with โˆ’, + and Reset buttons. It respects a minimum, a maximum and a step size, and it disables a button when pressing it would do nothing, which is clearer for users than a button that silently ignores clicks.

The logic is one pure function, nextValue(value, action, options). Actions are a literal union, so a misspelled 'incremnet' can't compile, and the switch covers every case, so TypeScript knows the function always returns a number. mountCounter connects that logic to four DOM-shaped objects and returns a read-only view of the current value through a getter:

TypeScript Stage 1: a counter with min, max and step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
start    shows 2  (- on, + on)
+        shows 6  (- on, + on)
+        shows 10  (- on, + off)
+ again  shows 10  (- on, + off)
- x3     shows 0  (- off, + on)
reset    shows 2  (- on, + on)
value read from the widget: 2

Notice that the second + stops at 10 instead of 14 (Math.min clamps it), the button turns off, and the third click is ignored the way a real disabled button ignores clicks. Three presses of โˆ’ go from 10 to 6, then 2, then 0 (clamped from โˆ’2).

A few type details:

  • textContent: string | null matches the real DOM, where textContent can be null on some node types. Matching the real type makes real elements assignable.
  • The return type { readonly value: number } gives callers a live value they can read but not assign, because the getter has no setter. See readonly and immutability.
  • FakeButton implements ButtonLike makes the compiler check the fake against the same interface as the real thing, so fakes can't drift away from what the widget expects.

Stage 2: show and hide a password

A "show password" button switches an input between type="password" and type="text". It must also tell assistive technology what it does: aria-pressed says whether the toggle is on, and the label changes between "Show password" and "Hide password". A widget that changes only the icon is invisible to screen reader users.

Here the DOM-shaped interface is deliberately narrower than the real DOM. A real input's type is just string, so input.type = 'txt' compiles in the browser and silently produces a text field. Our PasswordInput only allows 'password' | 'text', and setAttribute only accepts the two attribute names the widget uses:

TypeScript Stage 2: show and hide a password

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
type=password button="Show" aria-pressed=false
type=text button="Hide" aria-pressed=true
type=password button="Show" aria-pressed=false
hunter2: weak (use at least 12 characters, add a symbol)
sunflower-garden: okay (add a digit)
correct-horse-7: strong

mountPasswordToggle returns a small control object with a visible getter and a hide() method. That's a good habit for widgets: the page can hide the password again, for example right before the form is submitted, without reaching into the widget's internals. The strength check is another pure function: given a string, it returns a union value and a list of tips, so it's trivial to test.

What did the narrower type buy us? This:

TypeScript A typo in a DOM-shaped value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program doesn't run; the compiler reports main.ts(9,1): error TS2820: Type '"txt"' is not assignable to type 'PasswordFieldType'. Did you mean '"text"'? With the real HTMLInputElement, that typo would ship. In stage 4 you'll see how to connect the narrow interface to a real input with a small adapter.

Stage 3: a drag-and-drop list

The third widget is a list the user can reorder: a to-do list, playlist or the steps of a recipe. The browser's HTML drag-and-drop API sends dragstart on the item being dragged, dragover while it moves, and drop on the item under the pointer. The dragged item's ID travels in event.dataTransfer, a small store for the duration of one drag.

Drag and drop alone isn't enough, though: it needs a pointer, so it excludes keyboard users, and it's awkward on many touch devices. So the list also supports Alt+ArrowUp / Alt+ArrowDown on a focused item and announces each move in text ("Publish, position 2 of 4") for an aria-live region.

The logic is split into three layers:

  • moveItem<T>(items, from, to) is a generic pure function that returns a new array. It works for any item type and never mutates its input, which the readonly T[] parameter enforces.
  • ListEvent is a discriminated union of the three events the list understands, each with only the fields it needs. Inside case 'keydown', event.key and event.altKey exist; inside case 'drop', they don't.
  • createSortableList holds the current order, translates events into moves, and reports each change with an announcement.
TypeScript Stage 3: a reorderable list with drag and keyboard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints:

TEXT
a d b c   (Publish, position 2 of 4)
d a b c   (Write outline, position 2 of 4)
d b a c   (Write outline, position 3 of 4)
[ 'Publish', 'Draft chapter', 'Write outline', 'Edit' ]

Dropping "Publish" (d) on "Draft chapter" (b) moves it into b's position. The keyboard moves then push "Write outline" down twice. The last two key presses do nothing: "Edit" is already at the bottom, and the final press has no Alt key.

The default branch assigns event to a variable of type never. If you add a fourth event type, say { type: 'dragend' }, and forget to handle it, that line stops compiling, so the list can't silently ignore events you meant to support.

Stage 4: the browser code

Now connect everything to real elements. In a real project, each stage's logic lives in its own module (counter.ts, password-toggle.ts, sortable-list.ts) with export on the functions and types, and the fakes move into test files. The markup uses data-* attributes for configuration and an aria-live region for the list announcements:

HTML
<div data-counter data-min="0" data-max="10" data-step="2">
  <button type="button" data-minus aria-label="Decrease">โˆ’</button>
  <output>0</output>
  <button type="button" data-plus aria-label="Increase">+</button>
  <button type="button" data-reset>Reset</button>
</div>

<label for="password">Password</label>
<input id="password" type="password" autocomplete="new-password">
<button type="button" id="toggle-password">Show</button>

<ul id="steps">
  <li data-id="a">Write outline</li>
  <li data-id="b">Draft chapter</li>
  <li data-id="c">Edit</li>
  <li data-id="d">Publish</li>
</ul>
<p id="steps-status" aria-live="polite"></p>

The entry module finds the elements, checks them, and mounts the widgets. Compile it with the DOM library in tsconfig.json ("lib": ["es2024", "dom", "dom.iterable"]):

TypeScript
// src/main.ts (browser entry; tsconfig "lib": ["es2024", "dom", "dom.iterable"])
import { mountCounter } from './counter.js';
import { mountPasswordToggle } from './password-toggle.js';
import { createSortableList, type Item } from './sortable-list.js';

/** Find a required element and check its class at runtime. */
function requireElement<T extends Element>(
  root: ParentNode,
  selector: string,
  type: abstract new (...args: never[]) => T,
): T {
  const element = root.querySelector(selector);
  if (!(element instanceof type)) {
    throw new Error(`Expected ${type.name} for "${selector}"`);
  }
  return element;
}

// ---- counter ----
for (const root of document.querySelectorAll<HTMLElement>('[data-counter]')) {
  mountCounter(
    {
      output: requireElement(root, 'output', HTMLOutputElement),
      plus: requireElement(root, '[data-plus]', HTMLButtonElement),
      minus: requireElement(root, '[data-minus]', HTMLButtonElement),
      reset: requireElement(root, '[data-reset]', HTMLButtonElement),
    },
    {
      min: Number(root.dataset.min ?? 0),
      max: Number(root.dataset.max ?? 10),
      step: Number(root.dataset.step ?? 1),
    },
  );
}

// ---- password toggle ----
const passwordInput = requireElement(document, '#password', HTMLInputElement);
const toggleButton = requireElement(document, '#toggle-password', HTMLButtonElement);
mountPasswordToggle(
  {
    // adapter: our widget only ever writes 'password' or 'text'
    get type() {
      return passwordInput.type === 'text' ? 'text' : 'password';
    },
    set type(value) {
      passwordInput.type = value;
    },
    get value() {
      return passwordInput.value;
    },
    set value(text) {
      passwordInput.value = text;
    },
  },
  toggleButton,
);

// ---- sortable list ----
const listElement = requireElement(document, '#steps', HTMLUListElement);
const status = requireElement(document, '#steps-status', HTMLElement);

const initialItems: Item[] = [...listElement.querySelectorAll<HTMLLIElement>('li')].map((li) => ({
  id: li.dataset.id ?? '',
  label: li.textContent?.trim() ?? '',
}));

function renderList(items: readonly Item[]): void {
  listElement.replaceChildren(
    ...items.map((item) => {
      const li = document.createElement('li');
      li.textContent = item.label;
      li.dataset.id = item.id;
      li.draggable = true;
      li.tabIndex = 0;
      return li;
    }),
  );
}

const sortable = createSortableList(initialItems, (items, announcement) => {
  renderList(items);
  status.textContent = announcement; // #steps-status has aria-live="polite"
});
renderList(initialItems);

const itemIdOf = (target: EventTarget | null): string | null =>
  target instanceof HTMLElement ? (target.closest('li')?.dataset.id ?? null) : null;

listElement.addEventListener('dragstart', (event: DragEvent) => {
  const itemId = itemIdOf(event.target);
  if (itemId && event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move';
    sortable.handle({ type: 'dragstart', itemId, dataTransfer: event.dataTransfer });
  }
});

listElement.addEventListener('dragover', (event) => event.preventDefault()); // allow dropping

listElement.addEventListener('drop', (event) => {
  event.preventDefault();
  const itemId = itemIdOf(event.target);
  if (itemId && event.dataTransfer) {
    sortable.handle({ type: 'drop', itemId, dataTransfer: event.dataTransfer });
  }
});

listElement.addEventListener('keydown', (event: KeyboardEvent) => {
  const itemId = itemIdOf(event.target);
  if (itemId && (event.key === 'ArrowUp' || event.key === 'ArrowDown') && event.altKey) {
    event.preventDefault();
    sortable.handle({ type: 'keydown', itemId, key: event.key, altKey: event.altKey });
    listElement.querySelector<HTMLLIElement>(`li[data-id="${itemId}"]`)?.focus();
  }
});

What the types are doing here:

  • requireElement narrows with instanceof. querySelector returns Element | null; the class argument (HTMLButtonElement, HTMLOutputElement, โ€ฆ) is both a runtime check and the source of the return type T. A missing or wrong element fails loudly at startup with a clear message, instead of a Cannot read properties of null error on the first click. Its parameter type abstract new (...args: never[]) => T accepts any class constructor, whatever its constructor parameters are.
  • Real elements fit the stage interfaces. HTMLOutputElement has textContent; HTMLButtonElement has disabled and an addEventListener whose overloads include the 'click' form. TypeScript checks this structurally when you pass them in.
  • The password adapter bridges a wide type to a narrow one. passwordInput.type is string, our interface wants 'password' | 'text', so a getter maps the real value into the union and a setter writes it back. No assertion is needed, and the narrow type still guards the widget's own code.
  • event.dataTransfer is DataTransfer | null in the DOM types (it can be null for synthetic events), so the handlers check it. A real DataTransfer fits DataTransferLike, because its setData/getData accept any format string, including 'text/plain'.
  • Event types are inferred from the event name, as covered in TypeScript and the DOM. The explicit (event: DragEvent) and (event: KeyboardEvent) annotations are optional and only make the code easier to read.
  • li.draggable = true and tabIndex = 0 make each item draggable and focusable, so the keyboard shortcut can target it; after a move, focus returns to the moved item.

Ideas for extending the widgets

  • Give the counter keyboard support (ArrowUp/ArrowDown on the output, Home/End for min/max) by adding a 'min' | 'max' action to the union and handling it in nextValue.
  • Add a destroy() method to every control object and remove event listeners in it with an AbortController (addEventListener(type, listener, { signal })), then call it when the widget is removed from the page.
  • Turn the three mountโ€ฆ functions into custom elements (class CounterElement extends HTMLElement) and register them in HTMLElementTagNameMap so document.querySelector('acme-counter') returns the right type (see Declaration Files).
  • Write tests for each pure core with the mini test runner from Tooling, using the fake elements from stages 1โ€“3.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. mountCounter takes interface ButtonLike { disabled: boolean; addEventListener(type: 'click', listener: () => void): void }. Can you pass a real HTMLButtonElement?

    TypeScript's type system is structural. Any value with a compatible disabled property and addEventListener method fits ButtonLike, whether or not it declares the interface.
  2. 2. Why does stage 2 type the input's type as 'password' | 'text' instead of string?

    The real HTMLInputElement.type is a string, so any value compiles. The narrower interface catches mistakes; an adapter connects it to the real element.
  3. 3. In function handle(event: ListEvent), what does const unhandled: never = event; in the default branch do?

    If every case is handled, event is never in the default branch. A new, unhandled member would make that assignment a compile error, which points you to the missing case.
  4. 4. In the browser code, what is the type of event.dataTransfer inside a 'dragstart' listener?

    The DOM types declare dataTransfer as nullable, because synthetic drag events may not have one. The listener checks it before passing it to the widget.
  5. 5. Why does the sortable list also handle Alt+ArrowUp and Alt+ArrowDown?

    An accessible widget must work without a mouse. The keyboard path reuses the same moveItem logic and announces each move in an aria-live region.

Summary

  • Split every widget into a pure core (values in, values out) and a thin layer that talks to elements through DOM-shaped interfaces listing only what it uses.
  • Structural typing lets real elements fit those interfaces directly, and small fakes fit them too, so the logic runs and tests without a browser.
  • Interfaces can be narrower than the DOM ('password' | 'text' instead of string, typed attribute names) to turn silent bugs into compile errors; adapters bridge to the real element.
  • Model widget input as a discriminated union of events with a never check, and return small control objects (getters, hide(), destroy()) instead of exposing internals.
  • In the browser, find elements with an instanceof-checking helper, check nullable DOM properties such as dataTransfer, and keep widgets accessible: ARIA state, keyboard alternatives and live announcements.

Next: Project: Task Board