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

如何用Ajv定义含混合类型的列配置数组并修复TS编译错误?

如何修复Ajv嵌套列组Schema的TypeScript编译错误

需求背景

我需要用Ajv验证HTML表格的列头配置,支持两种结构:

  • 单列表:包含fieldOnlyColumnsCanHave字段(必填字符串)
  • 列组(堆叠表头):必须包含至少一个子项(子列组或单列表)

现有类型定义与Schema代码

单列表类型及Schema

interface ColumnConfiguration { 
  fieldOnlyColumnsCanHave: string; 
}

对应的Ajv Schema:

const columnConfigurationSchema: JSONSchemaType<ColumnConfiguration> = {
  type: 'object',
  properties: {
    fieldOnlyColumnsCanHave: { type: 'string' },
  },
  required: ['fieldOnlyColumnsCanHave'],
  additionalProperties: false,
};

列组类型及Schema

interface ColumnGroupConfiguration {
  children: (ColumnGroupConfiguration | ColumnConfiguration)[]; 
}

我编写的Schema如下(存在TS编译错误):

const columnGroupConfigurationSchema: JSONSchemaType<ColumnGroupConfiguration> =
  {
    $id: 'ColumnGroupConfiguration',
    type: 'object',
    properties: {
      children: {
        type: 'array',
        minItems: 1,
        items: {
          anyOf: [
            { $ref: 'ColumnGroupConfiguration' },
            columnConfigurationSchema,
          ],
        },
      },
    },
    required: ['children'],
    additionalProperties: false,
  };

根Schema

const columnsConfigurationSchema: JSONSchemaType<(ColumnGroupConfiguration | ColumnConfiguration)[]> = {
  type: 'array',
  items: {
    anyOf: [columnGroupConfigurationSchema, columnConfigurationSchema],
  },
  minItems: 1,
};

编译错误

columnGroupConfigurationSchema出现TypeScript编译错误:

The types of 'properties.children' are incompatible between these types

问题咨询

我临时用类型断言as JSONSchemaType<ColumnGroupConfiguration>绕过了错误,但不确定这种做法是否合理。请问如何正确修复这个Schema或TypeScript错误?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:47:55