Custom Elements Observe Typed Attributes

customElements.define with observedAttributes turns HTML attributes into a typed config surface, and an HTMLElementTagNameMap entry types createElement calls.

TypescriptConfig Management

Code

typescriptsnippet
37 lines
// Custom Elements: observedAttributes declares the config keys the component watches (its configuration surface),
// attributeChangedCallback reacts to each change
class UserBadge extends HTMLElement {
  static observedAttributes = ['name', 'role'];

  private displayRole = 'guest';

  connectedCallback(): void {
    this.render();
  }

  attributeChangedCallback(name: string, _oldValue: string | null, next: string | null): void {
    if (name === 'role') this.displayRole = next ?? 'guest';
    if (name === 'name') this.render();
  }

  private render(): void {
    this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
  }
}

customElements.define('user-badge', UserBadge);

// Declaration merging makes querySelector/createElement('user-badge') return UserBadge directly
declare global {
  interface HTMLElementTagNameMap {
    'user-badge': UserBadge;
  }
}

export {};

const badge = document.createElement('user-badge');
badge.setAttribute('name', 'Ada');
badge.setAttribute('role', 'admin');
document.body.append(badge);
console.log('badge renders:', badge.textContent);

Inside the snippet

Custom Elements Observe Typed Attributes is built around the class UserBadge.

Module-level bindings hold the data — badge — with no function scope in between.

What to watch for

  • A browser is the runtime here: document are not available in Node.

Putting it to use

Running the file prints labeled results such as badge renders: — each operation’s effect is visible in the output.

Core lines

this.textContent = `${this.getAttribute('name') ?? 'anon'} · ${this.displayRole}`;
if (name === 'role') this.displayRole = next ?? 'guest';

Interactive Tools for This Topic

FAQ

Does Custom Elements Observe Typed Attributes run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.