如何从官方OpenAPI Schema生成TypeScript接口与类?
如何自动生成OpenAPI 3.1 Schema对应的TypeScript接口/类
问题描述
我需要为官方OpenAPI 3.1的JSON Schema定义的对象(如Components对象、Schema对象)生成TypeScript接口或类。尝试过json-schema-to-typescript工具,但它无法处理$ref引用,且我无法通过解引用工具完成该Schema的解引用。核心目标是避免手动编写这些OAS定义的对象,请问是否可行?
期望生成的代码示例:
import openapiTS, { OpenAPI3, SchemaObject } from 'openapi-typescript'; declare module 'openapi-typescript' { export interface OpenAPI3 { findSchema: (path: string) => SchemaObject | undefined; } } OpenAPI3.prototype.findSchema = function (path: string): SchemaObject | undefined { const instance = OpenAPI3(this); return undefined; }
可行方案
- 直接复用成熟包的内置类型:
openapi-typescript包本身已经内置了OpenAPI 3.x全量的TypeScript类型定义,包括你需要的ComponentsObject、SchemaObject等所有OAS标准对象类型,无需自行从Schema生成,直接导入使用即可。 - 解决$ref解引用问题(自定义生成):如果必须从官方Schema生成,可使用
@apidevtools/json-schema-ref-parser工具处理循环引用和$ref解引用,之后再用json-schema-to-typescript生成类型:- 先将官方OpenAPI 3.1的Schema文件下载到本地(命名为
openapi31-schema.json) - 安装依赖:
npm install @apidevtools/json-schema-ref-parser json-schema-to-typescript --save-dev - 编写生成脚本:
const $RefParser = require('@apidevtools/json-schema-ref-parser'); const { compile } = require('json-schema-to-typescript'); const fs = require('fs'); async function generateOpenAPITypes() { // 加载并完全解引用本地的OpenAPI 3.1 Schema文件 const dereferencedSchema = await $RefParser.dereference('./openapi31-schema.json'); // 生成TypeScript类型文件 const tsCode = await compile(dereferencedSchema, 'OpenAPI31'); fs.writeFileSync('./openapi31-types.d.ts', tsCode); } generateOpenAPITypes();
- 先将官方OpenAPI 3.1的Schema文件下载到本地(命名为
- 扩展现有类型:如果需要给
openapi-typescript的内置类型添加自定义方法(如示例中的findSchema),直接使用TypeScript的模块扩展语法即可,无需重新定义所有基础类型。
内容的提问来源于stack exchange,提问作者integragreg
相关产品推荐
相关产品推荐

