How to define json schema for unknown type in TypeScript using ajv's JSONSchemaType

376 Views Asked by At

I am using AJV's JSONSchemaType to create a JSON schema that corresponds to a TypeScript interface with a property that can be of unknown type. However, TypeScript throws errors when trying to assign the schema.

Here's the TypeScript interface and the schema attempts:

import { JSONSchemaType } from "ajv";

interface OptionArray {
  options?: {
    title?: string;
    value: unknown;
  }[];
}

const schemaAttempt1: JSONSchemaType<OptionArray> = {
  type: "object",
  properties: {
    options: {
      type: "array",
      items: {
        type: "object",
        properties: {
          title: { type: "string", nullable: true },
          value: {}
        },
        required: ["value"],
        additionalProperties: false 
      },
      nullable: true
    }
  },
  required: [],
  additionalProperties: false
};

const schemaAttempt2: JSONSchemaType<OptionArray> = {
  type: "object",
  properties: {
    options: {
      type: "array",
      items: {
        type: "object",
        properties: {
          title: { type: "string", nullable: true },
          value: true
        },
        required: ["value"],
        additionalProperties: false 
      },
      nullable: true
    }
  },
  required: [],
  additionalProperties: false
};

First results in following ts error:

The types of 'properties.value' are incompatible between these types.
Type '{}' is not assignable to type '{ $ref: string; } | (UncheckedJSONSchemaType<unknown, false> & { nullable: true; const?: null | undefined; enum?: readonly unknown[] | undefined; default?: unknown; })'.

Second, very much like the first, results in similar ts error:

The types of 'properties.value' are incompatible between these types.
Type 'boolean' is not assignable to type '{ $ref: string; } | (UncheckedJSONSchemaType<unknown, false> & { nullable: true; const?: null | undefined; enum?: readonly unknown[] | undefined; default?: unknown; })'.

How can I properly define a json schema for a property with type unknown in TypeScript using ajv's JSONSchemaType?

Playground

1

There are 1 best solutions below

2
On

I haven't used AjvJsonSchemaType but an equivalent schema would be the following

{
  type: "object",
  properties: {
    options: {
      type: "array",
      items: {
        type: "object",
        properties: {
          title: { type: "string", nullable: true },
          value: { 
            "oneOf":[
              { "type": "string"},
              { "type": "object"},
              { "type": "boolean"},
              { "type": "number"},
              { "type": "array"},
              { "type": "null"}
            ]
        },
        required: ["value"],
        additionalProperties: false 
      }
    }
  },
  additionalProperties: false