Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda