Rob's garden / notes / note

Note

#javascript

After a bit of tinkering, this method seems nice for typing HTMLElements based on the classes you expect them to be.

You give it a query selector and a HTMLElement subclass you're expecting it to be. It'll then thrown an error if its missing or mis-typed. Then you have a strongly typed variable with that element. All in #JavaScript

code reading:

window.customElements.define("specs-icon", SpecsIcon); window.customElements.define("line-levels", LineLevels); window.customElements.define("media-devices", MediaDevices); window.customElements.define("status-led", StatusLED); window.customElements.define("time-window", TimeWindow);

const welcome = querySelectorAs("#welcome", HTMLDialogElement); const denied = querySelectorAs("#denied", HTMLDialogElement); const storage = querySelectorAs("#storage", HTMLDialogElement);

const source = querySelectorAs("#source", MediaDevices); const levels = querySelectorAs("#levels", LineLevels); const status = querySelectorAs("#status_light", StatusLED);

code reading:

/**

  • @template [T=HTMLElement] {HTMLElement}
  • @param {string} selector
  • @param {new (...args: any[]) => T} type */ export function querySelectorAs( selector, type = HTMLElement, parent = document, ) { const element = parent.querySelector(selector); if (!element) throw new TypeError("element not found " + selector); if (!(element instanceof type)) { throw new TypeError("invalid element"); } return element; }