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

如何实现JSON Schema实时转TypeScript类型及同schema同步校验

功能实现方案

方案1:纯TypeScript泛型实现(无构建依赖,推荐静态schema场景)

你需要的类型转换能力可以直接基于TypeScript类型系统实现,目前已有成熟的泛型工具库json-schema-to-ts满足需求,使用方式完全匹配你的预期:

  • 第一步:安装依赖
    npm install json-schema-to-ts
  • 第二步:代码示例
import { FromSchema } from "json-schema-to-ts";

// 注意必须加as const才能让TS正确读取schema的常量值
const jsonSchema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "number" },
  },
  required: ["name"],
} as const;

// 直接推导得到对应的TS类型
type SchemaType = FromSchema<typeof jsonSchema>;

// 业务代码使用示例
export default (input: SchemaType) => {
  // 可搭配任意JSON Schema运行时校验库使用,比如ajv
  validate(input, jsonSchema);
  // 后续业务逻辑
}
  • 适用场景:JSON Schema是代码中写死的静态常量,支持JSON Schema draft 7、2020-12等主流版本的几乎所有特性,生成的类型和常用在线转换工具输出效果一致。
  • 限制:如果你的JSON Schema是运行时动态生成的,无法在编译期确定具体结构,该方案无法生效。

方案2:webpack loader实现(支持动态schema场景)

如果需要处理动态加载或者批量的JSON Schema,你可以用json-schema-to-typescript库配合自定义webpack loader实现,该库和常见的在线转换工具底层转换逻辑一致,输出类型完全匹配:

  • 第一步:安装依赖
    npm install json-schema-to-typescript ts-loader
  • 第二步:编写自定义loader,新建文件json-schema-loader.js
const { compile } = require('json-schema-to-typescript');

module.exports = async function(source) {
  const schema = JSON.parse(source);
  // 编译schema为TS类型
  const tsTypeContent = await compile(schema, 'SchemaType', {
    bannerComment: '', // 去掉默认的生成注释
  });
  // 同时导出运行时schema对象和生成的类型
  return `export default ${JSON.stringify(schema)};\n${tsTypeContent}`;
}
  • 第三步:修改webpack配置新增loader规则
module.exports = {
  // 其他配置保持不变
  module: {
    rules: [
      {
        test: /\.schema\.json$/,
        use: ['ts-loader', './json-schema-loader.js'],
      }
    ]
  }
}
  • 第四步:使用示例
    将JSON Schema保存为后缀为.schema.json的文件,直接导入即可同时获取运行时校验用的schema对象和静态校验用的TS类型:
import jsonSchema, { SchemaType } from './user.schema.json';

export default (input: SchemaType) => {
  validate(input, jsonSchema);
  // 业务逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:09:03