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

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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