You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何验证对象符合TypeScript接口规范,具备所有要求的属性

TypeScript 接口属性校验方案

TypeScript 接口仅在编译阶段生效,运行时会被完全擦除,因此无法直接用接口校验运行时对象的属性是否完整,可通过以下两种方式实现:

方案1:手动编写类型守卫函数

逐字段编写校验逻辑,同时获得类型缩小能力:

// 校验 Vehicle 类型
function isVehicle(obj: unknown): obj is Vehicle {
  return typeof obj === "object" && obj !== null
    && "name" in obj && typeof (obj as Vehicle).name === "string"
    && "model" in obj && typeof (obj as Vehicle).model === "string"
}

// 校验 User 类型
function isUser(obj: unknown): obj is User {
  return typeof obj === "object" && obj !== null
    && "Name" in obj && typeof (obj as User).Name === "string"
    && "age" in obj && typeof (obj as User).age === "number"
}

// 校验 Customer 类型
function isCustomer(obj: unknown): obj is Customer {
  return isUser(obj)
    && "vehicles" in obj
    && Array.isArray((obj as Customer).vehicles)
    && (obj as Customer).vehicles.every(isVehicle)
}

使用时直接调用即可:

const targetObj = {} // 待校验对象
if (isCustomer(targetObj)) {
  // 校验通过,targetObj 会被TypeScript自动识别为Customer类型
}

方案2:使用运行时Schema库(推荐复杂场景使用)

以常用的 Zod 库为例,先定义Schema再推导TS类型,避免校验逻辑和类型定义重复维护:

  1. 先安装依赖:npm i zod
  2. 定义Schema并导出对应类型:
import { z } from "zod"

const VehicleSchema = z.object({
  name: z.string(),
  model: z.string()
})
type Vehicle = z.infer<typeof VehicleSchema>

const UserSchema = z.object({
  Name: z.string(),
  age: z.number()
})
type User = z.infer<typeof UserSchema>

const CustomerSchema = UserSchema.extend({
  vehicles: z.array(VehicleSchema)
})
type Customer = z.infer<typeof CustomerSchema>
  1. 校验对象:
const targetObj = {} // 待校验对象
const checkResult = CustomerSchema.safeParse(targetObj)
if (checkResult.success) {
  // 校验通过,checkResult.data 为Customer类型
} else {
  // 校验失败,可从checkResult.error获取具体错误信息
}

内容的提问来源于stack exchange,提问作者Edwin Guamushig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:06:05