0Pricing
TypeScript Academy · 课时

lib DOM 类型与 querySelector(严格空值检查)

理解 lib DOM 类型,并结合严格空值检查使用 querySelector 安全地选择元素。

lib DOM 类型与 querySelector(严格空值检查) 是 CoddyKit 上的免费 TypeScript Academy 课时。 这是第 1 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 TypeScript Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 TypeScript Academy 课程共包含 3 节课。

简介

目标:使用 DOM 库类型并安全地调用 querySelector。您将先检查 null,然后使用收窄后的类型调用元素 API。

DOM 库类型

TS 的 DOM 库为浏览器全局对象提供类型(例如 Document、HTMLElement、Event),从而支持 IntelliSense 和检查。

// DOM types come from the lib DOM definitions
// Examples: Document, HTMLElement, HTMLInputElement, Event

const title: string = document.title; // Document API
console.log("Title:", title);

querySelector 类型

querySelector 返回 Element | null。启用 strictNullChecks 后,您必须明确处理 null 情况。

const el = document.querySelector("#app");
// el: Element | null with strictNullChecks
console.log("Found?", el !== null);

提前返回守卫

请尽早进行守卫:检查 null,然后返回或抛出异常。完成守卫后,该分支中的变量就不会为 null。

function mount() {
  const root = document.querySelector("#app");
  if (!root) {
    console.warn("No #app found");
    return; // root is narrowed below only if present
  }
  // root: Element
  root.innerHTML = "<strong>Hello TS + DOM</strong>";
}

mount();

子类型收窄

使用 instanceof 进一步收窄到特定子类型,例如 HTMLInputElement,这样就可以使用元素专属的 API。

function readInputValue() {
  const input = document.querySelector("#name");
  if (!(input instanceof HTMLInputElement)) {
    return; // not an <input>
  }
  // input: HTMLInputElement
  console.log("value=", input.value);
}

readInputValue();

非 null 断言注意事项

除非您完全确定,否则请避免使用非 null 断言(!)。守卫可以让运行时更加安全。

function bad() {
  const root = document.querySelector("#app")!; // unsafe if #app missing
  // Potential runtime error below if root is actually null
  root.textContent = "unsafe";
}

// Prefer guarded version instead of non-null assertion

守卫模式检查

快速检查:在启用严格 null 检查的情况下执行 const el = document.querySelector("#app") 后,最安全的下一步是什么?

回顾

回顾:DOM 类型为 IntelliSense 提供支持。querySelector 返回 Element | null;请先进行守卫,再使用它。使用 instanceof 收窄类型,以调用元素专属的 API。

常见问题解答

「lib DOM 类型与 querySelector(严格空值检查)」课时是免费的吗?

是的 — 「lib DOM 类型与 querySelector(严格空值检查)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 TypeScript Academy 课程的其余内容,请升级到 CoddyKit PRO。 TypeScript Academy 课程共包含 3 节课。

「lib DOM 类型与 querySelector(严格空值检查)」这节课中我会学到什么?

理解 lib DOM 类型,并结合严格空值检查使用 querySelector 安全地选择元素。 你通过在浏览器中直接运行的动手代码来练习 TypeScript Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 TypeScript Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 TypeScript Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 3 节。

「lib DOM 类型与 querySelector(严格空值检查)」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 TypeScript Academy 课中编写并运行代码吗?

能。每节 TypeScript Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. lib DOM 类型与 querySelector(严格空值检查)
  2. 事件类型、自定义事件;收窄 HTMLElement 子类型
  3. 使用 FormData、URL 与 URLSearchParams
← 返回 TypeScript Academy