Creating nested interfaces in Typescript for modeling nested JSON objects

I am currently working on creating a nested JSON object and have defined an interface for it. However, I am encountering an error message stating that the type of property 'servicesAndHeads' is incompatible and it is missing. Here is my interface setup:

  interface Head {
    HeadNumber?: string;
    HeadDescription?: string;
  };

  interface ServicesAndHead {
    majorService?: string;
    subMajorService?: string;
    servicesAndHeads: Head[];
  }

  export interface MyTableItem {
   demandNo?: string;
   demandName?: string;
   servicesAndHeads?: ServicesAndHead;
   //servicesAndHeads?:ServicesAndHead[];
  }

This is how my JSON data is structured:

  const dataItem: MyTableItem =
  {
    demandNo: 'Demand Number 2',
    demandName: 'Animal Husbandary, Livestock, Fisheries and Veterinary Services',
    servicesAndHeads: [
    {
      majorService: 'C-Economic Service',
      subMajorService: '(a) Agriculture and Allied Activities',
      majorHead: [
       { majorHeadNumber: '3098', majorHeadDescription: 'Animal Husbandry' },
       { majorHeadNumber: '3999', majorHeadDescription: 'Diary Development' },
       { majorHeadNumber: '4902', majorHeadDescription: 'Fisheries' }
      ]
    },
    {
      majorService: 'C- Capital Account of Economic Services',
      subMajorService: '(a) Capital Account of Agriculture and Allied Activities',
      majorHead: [
        { majorHeadNumber: '0012', majorHeadDescription: 'Capital Outlay on Animal ' },
        { majorHeadNumber: '3245', majorHeadDescription: 'Capital Outlay on Fisheries' }
      ]
     }
   ]
  }

I have also attempted another approach for nesting 'servicesAndHeads':

  servicesAndHeads?: {
      [key: string]: ServicesAndHead,
      majorHeads?: {
        [key: string]: MajorHead
      };
  };

How can I correct my code to accommodate the given JSON structure?

Answer №1

Setting up Interfaces as outlined:

interface  Dome {
   mainDomeNumber?: string;
   mainDomeDescription?: string;
};

interface  ServicesAndDome {
   mainService?: string;
   subMainService?: string;
   mainDome: Dome[];
}

export interface MyTableContent {
   requestNo?: string;
   requestName?: string;
   servicesAndDomes?:ServicesAndDome[];
}

This format is tailored for your Json structure.

const information: MyTableContent = {

    requestNo: 'Request Number 2',
    requestName: 'Animal Husbandary, Livestock, Fisheries and Veterinary Services',
    servicesAndDomes: [
    {
       mainService: 'C-Economic Service',
       subMainService: '(a) Agriculture and Allied Activities',
       mainDome: [
       { 
          mainDomeNumber: '3098', 
          mainDomeDescription: 'Animal Husbandry' 
       },
       { 
          mainDomeNumber: '3999', 
          mainDomeDescription: 'Diary Development'
       },
       { 
          mainDomeNumber: '4902', 
          mainDomeDescription: 'Fisheries'
       }]
     },
     {
       mainService: 'C- Capital Account of Economic Services',
       subMainService: '(a) Capital Account of Agriculture and Allied Activities',
       mainDome: [
       { 
          mainDomeNumber: '0012', 
          mainDomeDescription: 'Capital Outlay on Animal '
       },
       { 
          mainDomeNumber: '3245', 
          mainDomeDescription: 'Capital Outlay on Fisheries'
       }]
     }]
    }

Answer №2

In the ServicesAndHead interface, it specifies that the servicesAndHeads property is required. However, the elements in the dataItem.servicesAndHeads array do not have this property; instead, they have a majorHead property. It seems like you intended for it to be like this:

interface ServicesAndHead {
  majorService?: string;
  subMajorService?: string;
  majorHead: Head[];
}

If this is the case, you will also need to update the Head interface as shown below:

interface Head {
  majorHeadNumber?: string;
  majorHeadDescription?: 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

Encountering problem decoding JSON in PHP

It's late, and the obvious solution seems to elude me. I'm struggling to decode this JSON string. {"result":{"transcription":"some message","guid":"something","identifier":null}} I've attempted plain json_decode($String) and even tried wal ...

Issue: Unable to create the restangular module because: the variable '_' is not defined

Upon integrating Restangular into an existing website, I encountered a JavaScript error that stated: Failed to instantiate module restangular due to: '_' is undefined I'm unsure of what this means. Can anyone clarify why '_' is ...

How to use AngularJS to add data to a nested array and then organize it based on a particular object within

As a newcomer to AngularJS, I am struggling to create a JSON-like nested array in my $scope.tabledata. Unfortunately, every time I click the add button, nothing seems to be happening. Any insights or suggestions would be greatly appreciated. For reference ...

The spaces between HTML elements within the pre tag are known as line gaps

I attempted to include some html tags within a pre tag, but noticed a significant gap between lines. Below is the HTML code I used: <h5>Help Message</h5> <pre ng-show="panel.info_mode == 'markdown'" ng-bind-html="panel.help_m ...

What is the best way to share data between Angular controllers using a localhost API connection?

When a button on my tr is clicked, I want to transfer the data within that tr to the next ng-controller. I've searched for a solution but it seems like I need to create an angular.module and connect the controllers together. Would it work with a local ...

Error: Angular does not recognize x2js XML format

I'm attempting to adapt this particular example to utilize xml as json data. However, I am encountering some issues with the code. courses = x2js.xml_str2json(data); console.log(courses.books.course); $scope.todos = courses.books.course; In the XML ...

Analyzing Variables Against SQL Columns in PHP

I'm trying to compare a variable to a column in my table and execute a query if the condition is met. Here's my PHP code, how should I modify it? $money_to_send = $_POST["money_to_send"]; $num_ban = $_POST["num_ban"]; if ($money_to_send < $so ...

Spring MVC causing JSON.stringify to become empty after second update request made through Ajax

Implementing an update functionality using jQuery AJAX with a JSON object can be challenging. The goal is to avoid refreshing the page every time a request is sent to a Spring MVC controller. Initially, a dataTable holds the data and when a row is clicked, ...

Employ ng-model within both directive and controller sources

Can the ng-model linked to the Controller be accessed in a Directive? <input type="text" ng-model="ctrl.valuelist.value" /> Controller: ctrl.valuelist.value = 'initial value'; Within the directive: function CustomDirective($window) { ...

Using Angular 6 pipes can simplify observable operations by eliminating the need for explicit typing

Recently, I upgraded my application from Angular5 to 6. Upon completing the update, I proceeded to migrate to rxjs6, which resulted in a change in my code where I was utilizing the takeWhile method. As a result, in order to subscribe to a service, my code ...

Verifying the Key in an Array after Decoding JSON Data

Is there a way to validate an array key from a JSON string that has been decoded from my SQL database? I find it easier to copy the field value directly rather than writing out lengthy codes. $ajaxcart = "{\"119\":[[\"Front Row\",119,5 ...

Using Django to Display a Line Chart with Data from a Dictionary in a Template

I have a dictionary that was generated in the views.py file. The structure of the dictionary is as follows, but it contains data for an unspecified number of enterprises: { enterprise1: {'Year': ['2014/2015', '2016/2017', &ap ...

Leveraging getStaticProps in Next.js

I am currently embarking on my inaugural Nextjs project, focused on developing a basic blog utilizing the JSON placeholder API. Strangely, I am encountering an issue where the prop "posts" is being perceived as undefined. Can anyone provide assistance with ...

User interface for dynamically generated elements using Typescript with React

Looking to create a translator hook that can pull language json files based on the selected language and return a portion of this large object depending on the arguments provided. How can I create an interface for an object that has been dynamically create ...

Verify if a JSON key is present in BigQuery

I need to determine if a specific key exists in a JSON object, and if it does, I want to return the entire JSON. Here is an example of the JSON data: json -------- "fruit":[{"apples":"5","oranges":"10&qu ...

Converting a Text file into JSON format

I have been working on converting a list of strings from a file into a specific JSON data format. The contents of my sample.txt file are as follows: 1234 5678 9765 The desired output format should be in the form of formatted.json: { "x": &qu ...

Efficiently storing a newly shuffled list of tasks into the db.json file using Angular

This is the content of my db.json document { "tasks": [ { "id": 1, "text": "Doctors Appointment", "day": "May 5th at 2:30pm", "reminder": true }, { ...

Has React.FC stopped utilizing PropsWithChildren?

From what I remember, you could write it like this: const SomeComponent:FC<{label: string}> = ({label, children}) => ( I came across some documentation that suggested it was possible. However, when I tried it with React version 18.2, I encountere ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

Is it possible for entities to transition between different use cases by means of the controller?

Currently, I am tasked with developing a route for processing ticket purchases for events. My approach involves utilizing a controller to handle incoming requests containing order data, client details, ticket information, and payment specifics. These reque ...