Which data type is the most suitable for a constant object in JSONSchemaType within AJV?

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" },
},

Answer №1

I developed a solution by specifying the $data reference within an if/then statement:

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" },
          },
        },
      },
    },
  },
};

Answer №2

A easier fix I found

details: {
  identifier: {
    type: "string",
    value: { $data: "/pathParameters/taskId" } as unknown as string,
  }
  ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

typescript logic description found

Currently, I am working on a React TypeScript project and have come across the following code: import { Trans, translate, InjectedTranslateProps } from 'react-i18next'; Following that, we have: export const Home: React.SFC<InjectedTranslate ...

Is there any event triggered when the src attribute of an image is modified?

I am currently working on a project where I am dealing with images of different sizes, and my goal is to adjust the parent div size based on the height of the new image. Within my code, I have set inner, viewOne, and viewTwo as global variables. Here is a ...

Explore the contents of a Table

When using a WebService, I send JSON to the front-end and map it to display all its content in a table. My goal is to implement a search method that will filter the rows based on searched letters. Component.ts allCountries: AllCountry[]; applyFilter(event ...

How can I retrieve the content of a JSON file and store it in an attribute of my

Just starting out with Angular 2 (first day!) I'm working on a class that has 3 fields: id and name which are passed to the constructor, and a third field called data which should hold the content of a JSON file. export class Hero { id: string; ...

Angular2 - Breaking down applications into reusable components

Utilizing custom properties permits seamless data binding between multiple components. <section id="main"> <app-home [dict]="dict">Hello there!</app-home> </section> In this scenario, dict serves ...

Hold on submitting the form with jQuery until the checkbox has been ticked

Hey there, I've added some jQuery code to validate a checkbox on a specific form. You can see a simple example on my JSFiddle. However, even if the checkbox is not clicked, the form still submits, but the alert message shows up. I'm trying to pr ...

Effortlessly Concealing Numerous Elements with a Single Click in Pure JavaScript

I have successfully created an HTML accordion, but I am facing an issue. I want to implement a functionality where clicking on one accordion button will expand its content while hiding all other accordion contents. For example, if I click on accordion one ...

The function "classList.add" does not successfully add a class to both a div and form elements

I've encountered an issue where I am unable to add a class to div/form elements using the classList.add method. Interestingly, this method works perfectly fine for other elements like input or button. However, when it comes to the div and form element ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

The changes in the dependency are not being updated in App Engine

Recently, I made a minor adjustment to one of the dependencies in my project. Surprisingly, it works flawlessly when tested locally. However, when deployed on the app engine, an error arises because the changes in the dependency are not being updated. Is ...

Adjusting the view with a sliding tool

I am new to jQuery and want to create a compact plugin for my specific needs. My goal is to develop a simple timeline plugin that looks like the example below: The green bar below contains two small rectangles that can be dragged left or right to zoom in ...

When can JavaScript objects hold up and when do they meet their demise?

Just diving into the world of Javascript, I stumbled upon an intriguing article that discussed the concept of reusing an ajax connection multiple times. The article gave an example: "You can define an ajax connection once, and reuse it multiple times, s ...

execute the execCommand function following an ajax request

I am currently developing a WYSIWYG editor and encountering an issue with image handling using execCommand. Here is a simplified example of my page structure: <div id="buttons_panel"><input id="img_submit" type="button"/></div> <div ...

Javascript ajax async data update has encountered a failure

Utilizing HTML, javascript, and Nodejs coding to create a chrome extension. When the page loads, the function getBalance() is invoked to retrieve data and display it in an HTML span. Below is the code snippet: function getBalance() { var request = new ...

Creating custom designs for a HTML button using CSS

Within an HTML form, there are two buttons set up as follows: <button kmdPrimaryButton size="mini" (click)="clickSection('table')">Table View</button> <button kmdPrimaryButton size="mini" (click)=&quo ...

What is the best way to present JSON data retrieved from an API on different pages using Next.js?

I am currently working on two pages that are connected: one is an API page called secured.js (where user session data is processed) and the other is a normal page also named secured.js (which displays the processed content from the API page). This is the ...

Question regarding the manipulation of attributes in Jquery

I'm a beginner with jQuery and struggling to find a solution for my issue. I have implemented jQuery easytooltip on some SVG elements in my website, which is working well. However, I need to dynamically change certain attributes of the tooltip when ne ...

Make sure to assign an id to the ng-template when using an Angular Bootstrap accordion

I'm struggling to assign a dynamic id to the heading template. I attempted to use id="{{group.title}}" but it doesn't seem to be working. Any assistance or suggestions would be greatly appreciated! <div ng-controller="AccordionDe ...

Typescript - Promise resolves prematurely

I have been given a code with three essential parts that cannot be altered: 1. First, there is a call to the getData function, followed by printing the output. getData().then(console.log); 2. The function signature is as follows: async getData(): Promise ...

Struggling to retrieve dataset from Bootstrap 5 form while using Angular

With the combination of Angular and Bootstrap 5, I have crafted this unique HTML form: <div class="mb-3"> <label for="genreName"> Type name</label> <div *ngIf="!enterTheGenre" class="form-group&qu ...