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

如何在TypeScript中动态检查JSON对象是否匹配指定接口?

能否直接用接口判断JSON对象是否完全匹配?

不行,你没法直接通过Matches(d, A)这种方式判断,因为TypeScript的接口是纯编译时类型——编译成JavaScript后,接口A和B会被完全擦除,运行时根本不存在这个“接口实体”,自然没法把它作为参数传给函数。

要实现对JSON对象的类型校验(包括完全匹配,即对象不能有定义外的额外属性),可以用以下几种方式:

1. 手写校验函数

针对接口的结构,手动编写检查逻辑,同时兼顾“完全匹配”的要求:

interface B {
  bar: string;
}

interface A {
  foo: string;
  bar: B;
}

// 校验B类型的函数,同时做类型守卫
function isB(obj: unknown): obj is B {
  if (typeof obj !== 'object' || obj === null) return false;
  const b = obj as B;
  // 检查属性类型+确保没有额外属性
  return typeof b.bar === 'string' && Object.keys(b).length === 1;
}

// 校验A类型的函数
function isA(obj: unknown): obj is A {
  if (typeof obj !== 'object' || obj === null) return false;
  const a = obj as A;
  // 检查foo类型、bar符合B结构+无额外属性
  return typeof a.foo === 'string' && isB(a.bar) && Object.keys(a).length === 2;
}

// 使用示例
const r = await fetch("https://mylink.com");
const d = await r.json();
const matches: boolean = isA(d);

这里的obj is A是TypeScript的类型守卫,调用isA(d)后,TypeScript会自动把d的类型推断为A(当返回true时)。

2. 使用Schema验证库

如果接口结构复杂,手写校验会很繁琐,可以用专门的运行时Schema验证库,比如Zod、io-ts。这类库允许你定义一份运行时可用的Schema,同时自动生成对应的TypeScript类型,不用重复编写类型定义:

以Zod为例:

import { z } from "zod";

// 定义运行时Schema,strict()确保无额外属性
const BSchema = z.object({
  bar: z.string()
}).strict();

const ASchema = z.object({
  foo: z.string(),
  bar: BSchema
}).strict();

// 自动生成TypeScript类型
type B = z.infer<typeof BSchema>;
type A = z.infer<typeof ASchema>;

// 使用示例
const r = await fetch("https://mylink.com");
const d = await r.json();
const result = ASchema.safeParse(d);
const matches: boolean = result.success;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:08:21