ajv icon indicating copy to clipboard operation
ajv copied to clipboard

Array `items` property should not be required in all array schemas

Open stuft2 opened this issue 3 years ago • 3 comments

What version of Ajv are you using? Does the issue happen if you use the latest version?

[email protected]

Your typescript code

const schema: JSONSchemaType<any[]> = { type: 'array' }

OR

const schema: JSONSchemaType<any[]> = { type: 'array', contains: { type: 'number' } }

Typescript compiler error messages

TS2322: Type '{ type: "array"; }' is not assignable to type 'UncheckedJSONSchemaType<any[], false>'.   Type '{ type: "array"; }' is not assignable to type '{ type: "array"; items: UncheckedJSONSchemaType<any, false>; contains?: UncheckedPartialSchema<any> | undefined; minItems?: number | undefined; ... 4 more ...; additionalItems?: undefined; } & { ...; } & { ...; }'.     Property 'items' is missing in type '{ type: "array"; }' but required in type '{ type: "array"; items: UncheckedJSONSchemaType<any, false>; contains?: UncheckedPartialSchema<any> | undefined; minItems?: number | undefined; ... 4 more ...; additionalItems?: undefined; }'.

Describe the change that should be made to address the issue?

When using the contains keyword, the items property should not be defined.

Json Schema Docs: https://json-schema.org/understanding-json-schema/reference/array.html#contains

type UncheckedJSONSchemaType<T, IsPartial extends boolean> = (
...
: T extends readonly any[]
      ? {
          type: JSONType<"array", IsPartial>
          items: UncheckedJSONSchemaType<T[0], false>
//        ^^^^ Should be made optional
          contains?: UncheckedPartialSchema<T[0]>
          minItems?: number
          maxItems?: number
          minContains?: number
          maxContains?: number
          uniqueItems?: true
          additionalItems?: never
        }
...
)

Are you going to resolve the issue?

This could be as simple as making the items property optional. This is the simplest and probably the most accurate solution.

PR https://github.com/ajv-validator/ajv/pull/1888

stuft2 avatar Jan 28 '22 16:01 stuft2

Possibly... It might be a breaking change, need to think.

Did you test if above examples compile with this change? I don't think any is adequately supported, but I might be wrong here...

epoberezkin avatar Feb 04 '22 18:02 epoberezkin

I've made the change in my node_modules/ajv/dist/types/json-schema.d.ts and the error goes away for both the examples above.

stuft2 avatar Feb 04 '22 21:02 stuft2

I also tried it with the type as JSONSchemaType<any[]> and JSONSchemaType<number[]> and didn't have any compile errors.

stuft2 avatar Feb 04 '22 21:02 stuft2