chikchakchok
chikchakchok

Reputation: 325

JsonSchema: how to create schema for inclusive array type?

Consider the following type:

type oneOfTwoPossibleArrays = 
    | [1, 2]
    | [3, 4]

What would the schema for it look like? This is my current failing attempt:
<Edit: this code works with ajv: ^8.2.0. I used 7.2.6 when I opened this post.>

const schema: JSONSchemaType<oneOfTwoPossibleArrays> = {
    oneOf: [
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 1 }, { type: 'number', const: 2 }]
        },
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 3 }, { type: 'number', const: 4 }]
        }
    ]
}

For some reason defining just one of the arrays in the schema doesn't generate typescript errors:

const schema: JSONSchemaType<oneOfTwoPossibleArrays> = {
    type: 'array',
    minItems: 2,
    maxItems: 2,
    items: [{ type: 'number', const: 1 }, { type: 'number', const: 2 }]
}

Upvotes: 1

Views: 314

Answers (1)

Stav Alfi
Stav Alfi

Reputation: 13953

Your code is working. You have caught an edge case where Ajv Typescript support is failing to compile your code:

// @ts-ignore.   // <<<<<----- ADD THIS LINE
const schema: JSONSchemaType<oneOfTwoPossibleArrays> = {
    oneOf: [
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 1 }, { type: 'number', const: 2 }]
        },
        {
            type: 'array',
            minItems: 2,
            maxItems: 2,
            items: [{ type: 'number', const: 3 }, { type: 'number', const: 4 }]
        }
    ]
}

You can open bug to Ajv github issue tracker to fix it on their side.

Upvotes: 1

Related Questions