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

使用typescript-fetch生成API时,如何将anyOf转为联合类型?

解决OpenAPI Generator生成TypeScript联合类型的问题

问题描述

使用OpenAPI Generator CLI 7.4.0基于给定的metric.json生成typescript-fetch代码时,Metric中value字段的anyOf定义(数字或数字数组)被生成了空的Value接口,而非预期的number | number[]联合类型。

解决方案

有两种可行方式实现预期的联合类型生成:

方法一:通过Schema扩展字段直接指定TypeScript类型

在OpenAPI Schema的value字段中添加x-typescript-type扩展,直接定义生成后的TypeScript类型:

修改后的metric.json:

// metric.json
{
  "openapi": "3.0.2",
  "info": { "title": "FastAPI", "version": "0.1.0" },
  "paths": {},
  "components": {
    "schemas": {
      "Metric": {
        "title": "Metric",
        "required": ["value"],
        "type": "object",
        "properties": {
          "value": {
            "title": "Value",
            "anyOf": [
              { "type": "array", "items": { "type": "number" } },
              { "type": "number" }
            ],
            "x-typescript-type": "number | number[]"
          }
        }
      }
    }
  }
}

重新执行生成命令后,Metric接口的value类型会直接变为number | number[],不会生成空的Value接口。

方法二:通过生成器配置全局处理anyOf为联合类型

在生成命令中添加--additional-properties=useAnyOfForUnionTypes=true参数,让OpenAPI Generator自动将anyOf定义转换为TypeScript联合类型:

$ npx openapi-generator-cli version
7.4.0
$ npx openapi-generator-cli generate -g typescript-fetch -o api -i ./metric.json --additional-properties=useAnyOfForUnionTypes=true

此配置会全局生效,所有Schema中的anyOf定义都会被转换成对应的TypeScript联合类型,无需逐个修改Schema。

验证结果

无论使用哪种方法,生成后的Metric.ts都会变成如下形式:

// api/models/Metric.ts
export interface Metric {
    /**
     * 
     * @type {number | number[]}
     * @memberof Metric
     */
    value: number | number[];
}

同时不会生成空的Value.ts文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:33:17