Currently, I am in the process of developing a validator utilizing AJV and have set up the schema in this manner:
const ajv = new Ajv({ allErrors: true, $data: true });
export interface UpdateTaskRequest {
pathParameters: {
listId: string;
taskId: string;
};
body: {
id: string;
name: string;
isCompleted?: boolean;
desc?: string;
dueDate?: string;
};
}
export const updateTaskRequestSchema: JSONSchemaType<UpdateTaskRequest> = {
$schema: "http://json-schema.org/draft-07/schema#",
type: "object",
properties: {
pathParameters: {
type: "object",
properties: {
listId: {
type: "string",
},
taskId: {
type: "string",
},
},
required: ["listId", "taskId"],
},
body: {
type: "object",
properties: {
id: {
const: { $data: "/pathParameters/taskId" },
},
name: {
type: "string",
maxLength: 200,
},
isCompleted: {
type: "boolean",
nullable: true,
},
desc: {
type: "string",
nullable: true,
maxLength: 400,
},
dueDate: {
type: "string",
nullable: true,
format: "date-time",
},
},
required: ["id", "name"],
},
},
required: ["pathParameters", "body"],
};
The main requirement is to ensure that body.id
matches pathParameters.taskId
, for which I used the const keyword along with the $data reference, as detailed here.
id: {
const: { $data: "/pathParameters/taskId" },
},
A hurdle I encountered is the following error message:
The types of 'properties.id' are incompatible between these types. Type '{ const: { $data: string; }; }' is not assignable to type '{ $ref: string; } | (UncheckedJSONSchemaType<string, false> & { const?: string | undefined; enum?: readonly string[] | undefined; default?: string | undefined; })'. Types of property 'const' are incompatible. Type '{ $data: string; }' is not assignable to type 'string'.ts(2322)
To address this issue, how can I instruct the TypeScript compiler that { $data: string; }
will eventually equate to string
in order to resolve the error mentioned above? Despite attempting the following solution, it did not yield any results:
id: {
type: "string",
const: { $data: "/pathParameters/taskId" },
},