Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda