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