Estoy escribiendo un validador usando AJV y he definido el esquema de la siguiente manera:
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"], }; Quiero validar que body.id es igual a pathParameters.taskId , así que utilicé la palabra clave const junto con la referencia de $data como se explica aquí .
id: { const: { $data: "/pathParameters/taskId" }, },El problema es que me sale el siguiente error:
Los tipos de 'properties.id' son incompatibles entre estos tipos. Escriba '{ const: { $datos: cadena; }; }' no se puede asignar al tipo '{ $ref: string; } | (UncheckedJSONSchemaType<string, false> & { const?: string | undefined; enum?: readonly string[] | undefined; default?: string | undefined; })'. Los tipos de propiedad 'const' son incompatibles. Escriba '{ $datos: cadena; }' no es asignable para escribir 'string'.ts(2322)
¿Cómo le digo al compilador de TypeScript que { $data: string; } eventualmente se resolverá en una string para resolver el error anterior? Intenté lo siguiente pero no funcionó:
id: { type: "string", const: { $data: "/pathParameters/taskId" }, },Encontré una solución al definir la referencia de $datos en una expresión si/entonces:
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: { type: "string", }, 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"], if: { properties: { pathParameters: { type: "object", properties: { taskId: { type: "string", }, }, }, }, }, then: { properties: { body: { type: "object", properties: { id: { const: { $data: "/pathParameters/taskId" }, }, }, }, }, }, };