具有联合类型的 ajv 数组

ajv array with union types

假设我有以下类型:

type MixedArray = Array<number | string>;

我希望有效的示例数据:

[ 'dfdf', 9, 0, 'sdfdsf' ]

如何创建一个 ajv JSONSchemeType 来验证预期的混合数组?

我尝试了以下方法:

import { JSONSchemaType } from 'ajv';

const Mixed: JSONSchemaType<MixedArray> = {
    type: 'array',
    items: {
        anyOf: [
            { type: 'number' },
            { type: 'string' },
        ]
    }

};

但是我收到一个打字稿错误:

Type '{ anyOf: ({ type: "number"; } | { type: "string"; })[]; }' is not assignable to type 'JSONSchemaType<string | number, false>'.

json-schema.d.ts(34, 5): The expected type comes from property 'items' which is declared here on type 'JSONSchemaType<MixedType, false>'

自从我发布问题后,我现在尽量避免编写联合类型。为了简单起见。

但是在示例情况下(或联合可以发挥优势的其他情况),我发现您可以通过键入带有 any 的联合来消除类型错误,并且架构仍将按预期工作(当然,只要依赖于模式的函数知道它是一个联合类型):

import { JSONSchemaType } from 'ajv';

const Mixed: JSONSchemaType<MixedArray> = {
    type: 'array',
    items: {
        anyOf: [
            { type: 'number' },
            { type: 'string' },
        ]
    }

} as any; // <----- add type declaration here

这种方法的缺点是您的模式不是强类型的。为此,我想你可以扩展 JSONSchemaType 来加强你的定义。