dom-hierarchy
Understand the DOM Hierarchy
Overview
TypeScript's DOM types accurately model the browser's DOM hierarchy. Understanding this hierarchy - Element extends Node, HTMLElement extends Element, etc. - helps you write correct DOM code. Use the most specific type possible for better autocompletion and type safety.
When to Use This Skill
- Working with DOM APIs
- Typing element references
- Creating DOM utilities
- Handling DOM events
- Manipulating the DOM
The Iron Rule
Use the most specific DOM type possible. HTMLElement for HTML elements, HTMLInputElement for inputs, etc.
DOM Type Hierarchy
EventTarget
└── Node
└── Element
└── HTMLElement
│ └── HTMLInputElement
│ └── HTMLButtonElement
│ └── etc.
└── SVGElement
Example
// BAD: Too general
const el: Element = document.getElementById('input');
el.value; // Error: Property 'value' doesn't exist on Element
// GOOD: Specific type
const input = document.getElementById('input') as HTMLInputElement;
input.value; // OK - value exists on HTMLInputElement
// Even better: Use querySelector with type parameter
const button = document.querySelector<HTMLButtonElement>('button.submit');
button?.disabled; // Typed correctly
Reference
- Effective TypeScript, 2nd Edition by Dan Vanderkam
- Item 75: Understand the DOM Hierarchy
More from marius-townhouse/effective-typescript-skills
precise-any-variants
Use when forced to use any. Use when any is too broad. Use when function types need any.
86narrow-any-scope
Use when any is unavoidable. Use when working with untyped libraries. Use when silencing specific type errors.
35tsdoc-comments
Use when documenting public APIs. Use when writing library code. Use when using JSDoc-style comments. Use when generating documentation. Use when explaining complex types.
33exhaustiveness-checking
Use when handling tagged unions. Use when adding new cases to discriminated unions. Use when switch statements must cover all cases.
13code-gen-independent
Use when confused about types at runtime. Use when trying to use instanceof with interfaces. Use when type errors don't prevent JavaScript output.
12tsconfig-options
Use when setting up a TypeScript project. Use when confused by type checking behavior. Use when strict mode causes unexpected errors.
11