Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
How to handle string or array type for a field in Ajv?

I have a field in my JSON that is supposed to hold the allowed values for a dropdown input.

[
  {
    "field": "status",
    "type": "select",
    "defaultValue": "open",
    "allowedValues": ["open", "pending", "closed"]
  },
  ...
]

This field must contain an array of strings or a token name (e.g. $allowedValues$) from which my code must pull the list of allowed values.

My problem is that I would like to use Ajv to validate the JSON, but apparently type string and array are not allowed to be used together.

enum InputType {
  SIMPLE = "simple",
  SELECT = "select",
  AUTOCOMPLETE = "autocomplete",
}

interface DefaultDefinition {
  ...
  type: InputType;
  allowedValues: string | string[];
}

const defaultDefinitionSchema: JSONSchemaType<DefaultDefinition> = {
  type: "object",
  properties: {
    ...
    type: {
      type: "string",
      enum: [InputType.AUTOCOMPLETE, InputType.SELECT, InputType.SIMPLE],
    },
    allowedValues: {
      type: ["array", "string"],
      items: { type: "string" },
    }
  },
  required: ["allowedValues"],
  additionalProperties: false,
};

Error message

Types of property 'type' are incompatible. Type '("string" | "array")[]' is not assignable to type '"array"'.

As a workaround I have considered adding another property called allowedValuesToken of type string and making the allowedValues a string array.

The problem with this approach is, that one of those properties must be required, but never both.

I was wondering if I can specify this via if/then, but I already have a if/then condition (I could not test it yet, due to my issue with the type of allowedValues) and it seems that since I have to define the absolute list of required fields in then/else (contrary to dynamically adding/removing single fields) this is not really feasible way either.

if: {
  properties: {
    type: {
      enum: [InputType.SIMPLE],
    },
  },
},
then: { required: ["type"] },
else: { required: ["type","allowedValues"] },

Can anyone tell me what is the proper way to it achieve my requirement?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!