instanceof Narrows DOM Element Types

instanceof checks double as type guards: each branch sees the concrete element class with its own properties instead of the bare Element shape.

TypescriptForm Validation

Code

typescriptsnippet
15 lines
// instanceof 在 TS 里同时完成两件事:运行时判断 + 类型收窄
const target: Element | null = document.querySelector('.profile');

if (target instanceof HTMLInputElement) {
  // 收窄为 HTMLInputElement:value / disabled / type 都可用
  console.log('input value:', target.value);
  target.disabled = true;
} else if (target instanceof HTMLAnchorElement) {
  // 收窄为 HTMLAnchorElement:href 可用
  console.log('anchor href:', target.getAttribute('href'));
} else if (target instanceof HTMLImageElement) {
  console.log('image alt:', target.alt);
} else {
  console.log('generic element:', target?.tagName ?? 'nothing matched');
}

Points of care

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

The demo output is labeled (input value:, anchor href:, image alt:), so each printed line points back to the operation it originated from.

Statements that matter

const target: Element | null = document.querySelector('.profile');
target.disabled = true;

Interactive Tools for This Topic

FAQ

Does instanceof Narrows DOM Element Types 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.