27 · DOM 与 Web API 类型系统
学完这章,你能读懂
lib.dom.d.ts的元素层级,用泛型把querySelector收窄到具体元素,并知道哪些null必须处理。
本章目标
- 能画出
EventTarget → Node → Element → HTMLElement的类型层级 - 能用
querySelector<T>与HTMLElementTagNameMap拿到具体元素类型 - 能正确处理
null、NodeList、HTMLCollection、dataset - 能区分「类型断言」与「运行时校验」,只在边界用断言
- 能读懂
TS18047与TS2339(DOM 场景)
前置知识
- 第 04 章(对象类型)、第 06 章(泛型)、第 08 章(联合)
- JavaScript DOM 基础(不熟可读
../javascript/docs/19-dom-events.md)
从你熟悉的语言出发
| 你熟悉的 | UI 类型层级 | TypeScript 的对应 | 关键差异 |
|---|---|---|---|
| Java Swing | Component → Container → JComponent |
Node → Element → HTMLElement |
DOM 层级由规范固定,不能自定义继承 |
| C++ Qt | QObject → QWidget |
EventTarget → Node → Element |
DOM 元素是宿主对象,不是普通类实例 |
| Android View | View → ViewGroup |
HTMLElement + 标签映射 |
DOM 没有布局类型,只有标签/接口 |
| 无对应 | 泛型查询 | querySelector<T> |
T 只是断言,运行时不校验 |
正文
27.1 lib.dom.d.ts 从哪来
TypeScript 自带 lib.dom.d.ts,由 lib: ["DOM"] 启用。它描述浏览器暴露的接口:
interface EventTarget { addEventListener(...): void; }
interface Node extends EventTarget { ... }
interface Element extends Node { ... }
interface HTMLElement extends Element { ... }
interface HTMLInputElement extends HTMLElement { value: string; }HTMLInputElement 的 value 不在 Element 上,所以 querySelector('#x').value 会报错——类型层级如实反映了「不是所有元素都有 value」。
27.2 querySelector 的泛型
const input = document.querySelector<HTMLInputElement>('#name');
// HTMLInputElement | null泛型参数是你的断言:编译器不会验证 #name 真的是 input。运行时若拿到 div,input.value 是 undefined。
更安全的写法是先用标签/属性判断:
const element = document.querySelector('#name');
if (element instanceof HTMLInputElement) {
element.value; // 收窄成功
}instanceof 会真的检查构造器,比泛型断言可靠。
27.3 HTMLElementTagNameMap
document.createElement 通过标签名映射返回具体类型:
document.createElement('button'); // HTMLButtonElement
document.createElement('input'); // HTMLInputElement
document.createElement('div'); // HTMLDivElementcreateElementNS 与自定义元素(第 30 章)也走各自的映射/扩展。
27.4 null、NodeList、HTMLCollection
| API | 返回类型 | 注意 |
|---|---|---|
querySelector |
Element | null |
必须判空 |
querySelectorAll |
NodeListOf<Element> |
有 forEach,但不是数组 |
getElementById |
HTMLElement | null |
比 querySelector 更具体 |
children |
HTMLCollection |
活的集合,会随 DOM 变化 |
childNodes |
NodeList |
包含文本节点 |
NodeListOf<T> 可以 for...of,但不能直接 .map;需要数组时用 Array.from(list)。
27.5 dataset 与 classList
const element = document.querySelector<HTMLElement>('[data-index]');
element?.dataset['index']; // string | undefined
element?.classList.add('active');dataset 是 DOMStringMap,键是动态的;基线 noPropertyAccessFromIndexSignature 要求方括号访问。classList 是 DOMTokenList,有 add/remove/toggle/contains。
27.6 表单与 FormData
const form = document.querySelector<HTMLFormElement>('form');
const value = new FormData(form).get('name'); // FormDataEntryValue | nullFormDataEntryValue 是 string | File,使用前要判断:
if (typeof value === 'string') { ... }27.7 断言的边界
as 在 DOM 场景常被滥用:
const canvas = document.querySelector('#canvas') as HTMLCanvasElement;
canvas.getContext('2d'); // 如果 #canvas 是 div,运行时报错合理做法:
- 选择器与泛型/断言紧挨着写,并在注释里说明为什么确定。
- 需要绝对安全时用
instanceof或tagName校验。 - 在边界(第三方脚本插入的 DOM、SSR 水合)做运行时校验。
类型错误现场
examples/27-dom-web-types/04-nullability/demo/possibly-null.ts:
const input = document.querySelector<HTMLInputElement>('#name');
export const value = input.value;真实报错(TypeScript 7.0.2):
demo/possibly-null.ts(5,22): error TS18047: 'input' is possibly 'null'.TS18047是strictNullChecks下最常见的 DOM 错误。- 修复:
if (input === null) return ...,或input?.value。 - 若写成
document.querySelector('#name').value,会先报TS2339(Element上没有value),再报TS18047。
反直觉差异:querySelector 返回的不是 HTMLElement
你的直觉:document.querySelector('div') 明明返回一个 div,类型应该是 HTMLDivElement。
实际行为:类型是 Element | null,因为选择器是运行时字符串,编译器无法知道匹配到什么:
const element = document.querySelector('div'); // Element | null
element.style; // error:Element 上没有 style要访问 style,必须收窄:
const element = document.querySelector('div');
if (element instanceof HTMLElement) {
element.style.color = 'red';
}为什么这样设计:DOM 的查询 API 接受任意 CSS 选择器,结果可能是任意元素、文本、注释,也可能为空。类型系统不能对运行时字符串做静态解析(CSS 选择器不是 TypeScript 的子语言)。泛型参数是「你告诉编译器答案」,不是「编译器验证答案」。
正确写法:
- 能用
getElementById/createElement就用,它们返回更具体的类型。 - 用
instanceof/tagName做运行时收窄。 - 泛型只在你确定选择器唯一且标签稳定时使用,并写注释。
示例索引
| 目录 | 演示什么 | 预期看到 |
|---|---|---|
examples/27-dom-web-types/01-query-selector/ |
querySelector<T> 与判空 |
Ada |
examples/27-dom-web-types/02-tag-name-map/ |
createElement 映射 |
BUTTON、true |
examples/27-dom-web-types/03-dataset-forms/ |
dataset 与 FormData |
3、Ada |
examples/27-dom-web-types/04-nullability/ |
可空处理 | Ada;失败配置贴 TS18047 |
练习题
- 把
examples/27-dom-web-types/01-query-selector改成instanceof HTMLInputElement收窄,比较与泛型断言的差别。 - 给
03-dataset-forms增加一个多选<select multiple>,用FormData.getAll读出数组。 - 写一个
assertElement<T extends Element>(value: Element | null, ctor: new () => T, label: string): T,在边界处替代as。
const element = root.querySelector('#name'); if (!(element instanceof HTMLInputElement)) return '(missing)'; return element.value;。泛型断言更短但不校验;instanceof会真的检查。new FormData(form).getAll('tags')返回FormDataEntryValue[],过滤typeof === 'string'。- 用
value instanceof ctor判断,失败抛错;ctor类型可用abstract new (...args: never[]) => T兼容更多元素类。
章末自检
querySelector默认返回什么类型?为什么不是HTMLElement?createElement('button')的类型从哪来?NodeList和数组有什么区别?dataset为什么建议用方括号访问?FormData.get返回什么类型?如何安全使用?TS18047在什么配置下才会出现?
Element | null;选择器是运行时字符串,编译器无法确定标签。HTMLElementTagNameMap。NodeList是类数组,有forEach但不是Array,没有map/filter。- 键是动态的,
noPropertyAccessFromIndexSignature要求索引访问。 FormDataEntryValue | null(string | File | null);先判空与typeof。strictNullChecks(strict的一部分)开启时。
延伸阅读
- TypeScript 自带
lib.dom.d.ts(EventTarget、Node、Element、HTMLElement) - MDN:Document.querySelector、HTMLElementTagNameMap、FormData
- JavaScript 教程
../javascript/docs/19-dom-events.md(DOM 行为) - HTML Standard §3 Semantics, structure, and APIs of HTML documents