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

168
Visualizações
ajv - Ensure that given object structure matches structure of a custom type

I'm using ajv with TypeScript and have a custom type MyCustomType. When creating a validation schema I want to ensure that a specific property is of type MyCustomType. So ajv should validate its structure and decide whether this could be parsed to the given type.

I started with the following sample code ( and created a Codesandbox example for testing purposes )

import { AType } from "./AType"; // custom type
import { AnInterface } from "./AnInterface"; // custom interface
import Ajv from "ajv";

type MyComplexType = AType | AnInterface; // create a more complex type from the given imports

const ajvInstance = new Ajv();

const schema = {
  type: "object",
  properties: {
    myComplexType: { type: "string" } // value structure must match structure of  MyComplexType
  },
  required: ["myComplexType"],
  additionalProperties: false
};

const validate = ajvInstance.compile(schema);

const data = {
  myComplexType: {}
};

const isValid = validate(data);

if (isValid) {
  console.info("everything is fine");
} else {
  validate.errors?.forEach((error) => console.error(error.message));
}

Currently I don't know how to create a validation schema for the property myComplexType. I found some discussions

  • Add instanceof property for type objects
  • Creating a custom type
  • Type keywords

but I don't think these will help because

  • typeof just returns "object"
  • instanceof won't work for types

So do I have to create a custom keyword ( as described here ) and write my own validation logic ( inspect the object structure ) or are there any things I can already use? How should I configure myComplexType?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't think you can create a custom type with this library, maybe you're confusing javascript types with typescript types. So you probably have 2 options: 1) instead of using types you use classes and use instanceof for validating an instance of your class, e.g.

class MyClass {}
const instanceofDef = require("ajv-keywords/dist/definitions/instanceof")
instanceofDef.CONSTRUCTORS.MyClass = MyClass
ajv.validate({instanceof: "MyClass"}, new MyClass())

or 2) you create a nested schema like this

const schema = {
  type: "object",
  properties: {
    myComplexType: { 
      type: "object",
      properties: {
        myProperty: { type: "string" },
        myFunction: { type: "function" },
        ...
      }
    }
  },
  required: ["myComplexType"],
  additionalProperties: false
};

const validate = ajvInstance.compile(schema);

const data = {
  myComplexType: {
    myProperty: "Hello World",
    myFunction: function(){}
  }
};

const isValid = validate(data);
about 4 years ago · Juan Pablo Isaza Relatório
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