TypeScript 接口数据实战:unknown、类型守卫与运行时校验

简介: 本文以库存查询为例,讲解如何用 TypeScript 安全处理 API 响应:将 `response.json()` 视为 `unknown`,通过类型守卫、解析函数校验结构/范围/可选字段,将校验失败转为明确 UI 状态,避免运行时异常。

前端调用接口时,为 response.json() 标注 TypeScript 类型不会自动校验服务器返回的数据。字段缺失、数值类型变化和嵌套对象结构错误都可能在运行时产生异常。本文以库存查询为例,将网络边界设为 unknown,通过类型守卫和解析函数建立可信数据,并把校验失败转换为明确的界面状态。

下列代码块按各节独立展示,实际接入时应结合相应的样式、脚本或组件文件。

1. 区分类型声明与真实数据

接口类型描述应用期望的结构,但不能改变实际响应。应先把网络输入接收为 unknown,再验证字段。以下库存卡片只能在数量校验成功后展示数值。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/9968e81dcb63c3d5b02eeafcc6bb7543f8892c68">
  <article class="stock-card"><h2 data-product-name>库存商品</h2><output data-stock-count>待加载</output></article>
</div>
type Product = {
    id: string; name: string; stock: number };
async function readUnknown(response: Response): Promise<unknown> {
   
  if (!response.ok) throw new Error(`HTTP ${
     response.status}`);
  const body: unknown = await response.json();
  return body;
}

2. 先判断对象边界

typeof null 的结果是 object,数组也属于对象。因此在读取字段之前应排除 null 和数组。守卫这里只用于 JSON 对象的结构检查,不把它当作判断任意 JavaScript 对象安全性的工具。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a5d37d9a44d7b56c061d41212d31f619d55f8f63">
  <section class="stock-response"><h2>响应检查</h2><p data-shape-status role="status">等待数据</p></section>
</div>
function isRecord(value: unknown): value is Record<string, unknown> {
   
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}

3. 校验数值的业务范围

只判断 typeof value === number 无法排除 NaN、Infinity 或负数。库存应为非负安全整数;金额、百分比或权重则需要各自的领域约束,不能共用一条模糊的数字校验。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/2e6f65d0dd4013766bbf6058b7f840329f3ffb02">
  <section class="quantity-preview"><label>当前库存<output data-quantity>未确认</output></label><p data-quantity-error role="alert"></p></section>
</div>
function isStock(value: unknown): value is number {
   
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
}

4. 构建可读的记录解析函数

类型谓词由开发者保证正确性,编译器不会验证守卫是否真的检查了所有字段。对于接口边界,可以直接构造经过验证的 DTO,这样额外字段也不会不经处理地传播到组件。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3771b3b79e40ed7d709371ccd07c25a551db2db8">
  <article class="product-preview"><h2 data-name></h2><p>编号:<span data-product-id></span></p><p>库存:<output data-stock></output></p></article>
</div>
function parseProduct(value: unknown): Product {
   
  if (!isRecord(value) || typeof value.id !== 'string' || !value.id || typeof value.name !== 'string' || !isStock(value.stock)) {
   
    throw new TypeError('Invalid product payload');
  }
  return {
    id: value.id, name: value.name, stock: value.stock };
}

5. 数组响应逐条验证

Array.isArray 只验证容器,不验证其中的记录。对库存列表而言,静默丢弃非法记录可能造成统计错误,所以此处选择任意一条不合格就拒绝整批数据,并把错误交给上层处理。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a0b72e92a66a0430564de512a3a06595008bf2cf">
  <section class="stock-list"><h2>库存列表</h2><ul data-stock-items></ul><p data-list-error role="alert"></p></section>
</div>
function parseProducts(value: unknown): Product[] {
   
  if (!Array.isArray(value)) throw new TypeError('Expected an array');
  return value.map((item: unknown) => parseProduct(item));
}

6. 处理可选字段和 null

字段缺失与显式 null 在接口中可能有不同含义。示例约定备注可缺失但如果存在必须是字符串;如果服务端允许 null,应在类型及解析函数中明确体现,而非使用非空断言绕过。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/0d0986a75b9221d2886d09123922ea7659736438">
  <article class="product-note"><h3>库存备注</h3><p data-note>暂无备注</p></article>
</div>
type ProductWithNote = Product & {
    note?: string };
function parseProductWithNote(value: unknown): ProductWithNote {
   
  const product = parseProduct(value);
  if (!isRecord(value)) throw new TypeError('Invalid record');
  const note = value.note;
  if (note === undefined) return product;
  if (typeof note !== 'string') throw new TypeError('Invalid note');
  return {
    ...product, note };
}

7. 在网络层统一建立可信边界

组件无需反复判断 stock 是否为数字。API 模块完成 HTTP 状态处理、JSON 读取和结构校验,之后才将明确类型交给展示层。错误提示应避免直接展示内部服务响应。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/35cd1547a7cf0e7e54d4c946272cfaec75538f9a">
  <section class="inventory-actions"><button type="button" data-refresh>刷新库存</button><p data-load-status role="status"></p></section>
</div>
async function loadProducts(signal: AbortSignal): Promise<Product[]> {
   
  const response = await fetch('/api/products', {
    signal });
  return parseProducts(await readUnknown(response));
}

8. 错误对象也来自 unknown

catch 中捕获的值可能是 Error、字符串或其他对象。使用 instanceof Error 获取常见错误描述,但向用户显示的内容应按业务分类映射;不要直接把任意对象拼进 HTML。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6b704478e0db7d11659844d36dd864f443885ef2">
  <aside class="inventory-error"><p data-error role="alert"></p><button type="button" data-retry>重新加载</button></aside>
</div>
function describeFailure(error: unknown): string {
   
  if (error instanceof DOMException && error.name === 'AbortError') return '请求已取消';
  if (error instanceof TypeError) return '数据读取或校验失败';
  return '暂时无法加载库存';
}

9. 校验通过仍需安全渲染

字符串通过类型校验不代表可以当成 HTML 使用。展示商品名称应使用 textContent 或框架默认的转义插值。授权、价格和库存扣减依然需要由服务端进行最终判断。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f200d8339bffbdc1bbf2701d37d5331d490f24ab">
  <article class="safe-stock"><h2 data-safe-name></h2><output data-safe-stock></output></article>
</div>
function renderProduct(root: HTMLElement, product: Product): void {
   
  const name = root.querySelector('[data-safe-name]');
  const stock = root.querySelector('[data-safe-stock]');
  if (name) name.textContent = product.name;
  if (stock) stock.textContent = String(product.stock);
}

10. 用非法输入反向验证契约

测试解析函数时应构造 null、缺失字段、字符串数字、负数、超出安全整数范围和合法零库存。以下是可直接执行的断言示例,不代表已运行过完整项目的测试。

<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/14c614a55eeb393861f2bd9f11ed2e369dc47b43">
  <section class="contract-checks"><h2>接口契约验证</h2><ul><li>零库存属于合法结果</li><li>字符串数字不自动转换</li><li>非法记录阻止整批展示</li></ul></section>
</div>
function checkProductContract(): void {
   
  if (parseProduct({
    id: 'p1', name: '配件', stock: 0 }).stock !== 0) throw new Error('zero rejected');
  for (const invalid of [null, {
   }, {
    id: 'p1', name: '配件', stock: '5' }, {
    id: 'p1', name: '配件', stock: -1 }]) {
   
    let rejected = false;
    try {
    parseProduct(invalid); } catch {
    rejected = true; }
    if (!rejected) throw new Error('invalid payload accepted');
  }
}

总结

TypeScript 的静态类型应建立在可信的运行时数据之上。将 unknown 限制在输入边界,通过解析函数明确结构、范围和可选字段规则,再让组件消费验证后的模型,比在整个项目中散布 as 类型断言更可维护。

相关文章
|
2天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8072 2
|
11天前
|
域名解析 人工智能 Linux
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
10169 13
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
10天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1531 5
|
9天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2682 8
|
9天前
|
Web App开发 缓存 安全
巨魔商店 TrollStore 安装教程(2026):免电脑在线安装与全机型安装器矩阵_iOS巨魔安装
巨魔商店(TrollStore)是iOS 14–17.0(特定版本)的永久签名工具,无需越狱,利用CoreTrust漏洞实现IPA签名长期有效,彻底告别7天重签。支持免电脑在线安装(TrollHelperOTA),适配多机型/系统组合,开源免费,安全可控。(239字)
2284 0