'Json Schema which has at least one of any properties (or more) with ajv

I am trying to build a simple Json schema (at least that's what I thought) which contains two properties foo and bar.

It should validate when:

  • foo is in the json and no other properties
  • or bar is in the json and no other properties
  • or foo and bar are in the json and no other properties.

I am using ajv and Typescript and this is the code:

interface MyData {
  foo: number;
  bar: string;
}

const schema: JSONSchemaType<MyData> = {
  type: 'object',
  minProperties: 1,
  properties: {
    foo: { type: 'integer' },
    bar: { type: 'string' },
  },
  additionalProperties: false,
};

However Typescript forces me to add a required field, and if I do, it works but this means that at least one specific property is always required which is not what I want. I am not sure if this my wrong understanding of JsonSchema or if this is a Typescript implementation issue of ajv.



Solution 1:[1]

So the answer is just too obvious but I will still post it here if someone else gets also stuck.

I just added an empty required property like so:

require:[]

For some reason I did not think this is allowed, but it works...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zlZimon