为什么该JSON Schema无法赋值给对应的TypeScript接口类型?
报错原因
存在两处类型不匹配问题:
- 字段类型定义错误:你在schema的
changes数组项规则中,将old、new字段的类型设置为string,但ExpectedBody接口中这两个字段是包含name属性的对象,二者类型完全不兼容。 - 元组与普通数组定义不匹配:接口中
changes的类型是[{old:..., new:...}],属于TypeScript固定长度为1的元组类型,要求数组必须有且仅有1个符合规则的元素;但你在schema中将该字段定义为minItems: 0的普通数组,和元组的类型要求不符。
修复方案
可根据你的实际业务需求二选一:
方案1:确实需要changes为固定长度1的元组
调整schema的changes字段配置,同时修正old、new的类型定义:
import Ajv, { JSONSchemaType } from 'ajv' interface ExpectedBody { repository: { name: string, } push: { changes: [{ old: { name: string, }, new: { name: string, } }] } } const expectedBodySchema: JSONSchemaType<ExpectedBody> = { type: 'object', properties: { repository: { type: 'object', properties: { name: { type: 'string', }, }, required: ['name'], }, push: { type: 'object', properties: { changes: { type: 'array', // 匹配元组固定长度1的要求 minItems: 1, maxItems: 1, // 元组的items需要用数组格式,对应每个位置的元素规则 items: [ { type: 'object', properties: { old: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, new: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, }, required: ['old', 'new'] } ], }, }, required: ['changes'] } }, required: ['repository', 'push'], }
方案2:需要changes为任意长度的普通数组
先修改接口定义,将元组改为普通数组,再对应调整schema:
import Ajv, { JSONSchemaType } from 'ajv' interface ExpectedBody { repository: { name: string, } push: { // 元组改为普通数组定义 changes: Array<{ old: { name: string, }, new: { name: string, } }> } } const expectedBodySchema: JSONSchemaType<ExpectedBody> = { type: 'object', properties: { repository: { type: 'object', properties: { name: { type: 'string', }, }, required: ['name'], }, push: { type: 'object', properties: { changes: { type: 'array', minItems: 0, items: { type: 'object', properties: { old: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, new: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, }, required: ['old', 'new'] }, }, }, required: ['changes'] } }, required: ['repository', 'push'], }
内容的提问来源于stack exchange,提问作者user1283776
相关产品推荐
相关产品推荐

