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

OpenAPI Generator仅生成接口,如何为Angular TS项目生成类?

解决OpenAPI Generator生成类而非接口及type: object被忽略的问题

一、配置生成类而非接口

OpenAPI Generator的TypeScript Angular生成器默认输出接口,通过以下方式修改配置生成类:

1. 命令行直接指定参数

运行生成命令时添加--additional-properties参数,开启类生成及可选的构造函数生成(方便实例化):

npx @openapitools/openapi-generator-cli generate \
  -i swagger.json \
  -g typescript-angular \
  -o ./src/app/generated \
  --additional-properties useClass=true,generateModelsWithConstructors=true
  • useClass=true:强制生成类而非接口
  • generateModelsWithConstructors=true:自动生成带参数的构造函数,便于快速创建实例

2. 使用配置文件(推荐,便于复用)

创建openapi-generator-config.yaml配置文件:

generatorName: typescript-angular
inputSpec: ./swagger.json
outputDir: ./src/app/generated
additionalProperties:
  useClass: true
  generateModelsWithConstructors: true
  modelPropertyNaming: original # 保持属性名与swagger.json一致,避免自动驼峰转换(可选)

然后执行生成命令:

npx @openapitools/openapi-generator-cli generate -c openapi-generator-config.yaml

二、解决"type": "object"被忽略的问题

按以下步骤排查和修复:

1. 检查swagger.json的schema结构是否合规

确保type: object的定义在components/schemas下,且包含必要的properties字段(空对象需显式声明):

"components": {
  "schemas": {
    "EmptyObject": {
      "type": "object",
      "properties": {} // 空对象需显式添加空properties,否则可能被忽略
    },
    "User": {
      "type": "object",
      "properties": {
        "id": { "type": "integer" },
        "profile": { "type": "object" } // 嵌套对象的定义
      }
    }
  }
}

如果是参数或响应中的type: object,需确保正确嵌套在schema字段下:

"paths": {
  "/users": {
    "post": {
      "requestBody": {
        "content": {
          "application/json": {
            "schema": { "type": "object", "properties": { "name": { "type": "string" } } }
          }
        }
      }
    }
  }
}

2. 排除$ref或多态定义的干扰

如果type: object的schema同时使用了$ref、anyOf或oneOf,生成器可能优先处理引用或多态逻辑,导致type被覆盖。此时需调整schema结构:

  • 避免在同一个schema中同时使用$ref和type
  • 多态场景下,明确指定discriminator字段

3. 更新OpenAPI Generator到最新版本

旧版本可能存在type: object解析的bug,执行以下命令升级:

npm update -g @openapitools/openapi-generator-cli

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:47:13