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

如何正确定义元素为对象的数组JSONSchema并解决TS类型报错

问题原因

你在ExpectedBody3中定义的changes字段为长度固定为1的元组类型(TypeScript中[T]语法代表仅包含1个T类型元素的元组,和任意长度的T[]普通数组类型规则不同)。JSONSchemaType对元组类型有强制约束:必须显式声明minItems、maxItems匹配元组长度,且items字段需要用数组形式声明对应位置的元素schema,你原有代码未满足该约束,因此触发类型报错。

解决方案

根据你的实际需求选择以下任意一种方案即可:

方案1:保留元组类型(要求changes必须只有1个元素)

修改schema配置,补充元组对应的必填属性:

interface ExpectedBody3 {
  push: {
    changes: [{
      old: string,
    }]
  }
}

const expectedBodySchema3: JSONSchemaType<ExpectedBody3> = {
  type: 'object',
  properties: {
    push: {
      type: 'object',
      properties: {
        changes: {
          type: 'array',
          // 元组对应items用数组声明每一位元素的schema
          items: [
            {
              type: 'object',
              properties: {
                old: {
                  type: 'string'
                },
              },
              required: ['old']
            }
          ],
          // 补充和元组长度匹配的minItems、maxItems
          minItems: 1,
          maxItems: 1
        },
      },
      required: ['changes']
    }
  },
  required: ['push'],
}

方案2:改为普通对象数组(changes可包含任意数量符合规则的元素)

修改接口定义,将元组类型改为普通数组类型,原有schema无需改动:

// 仅修改接口中changes的类型定义即可
interface ExpectedBody3 {
  push: {
    changes: {
      old: string,
    }[]
  }
}

const expectedBodySchema3: JSONSchemaType<ExpectedBody3> = {
  type: 'object',
  properties: {
    push: {
      type: 'object',
      properties: {
        changes: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              old: {
                type: 'string'
              },
            },
            required: ['old']
          },
        },
      },
      required: ['changes']
    }
  },
  required: ['push'],
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:24:06