Typescript interface design for nested objects in a hierarchical structure

When data is received from the server in JSON format, it typically looks like the example below (details have been modified):

{
  "apple": {
    "fruitName": "apple",
    "types": {
      "greenApple": {
        "productCode": "P1",
        "productName": "Green Apple",
        "color": "green",
      },
      "galaApple": {
        "productCode": "P2",
        "productName": "Gala Apple",
        "color": "light red",
      },
      "redDelicious": {
        "productCode": "P3",
        "productName": "Red delicious apple",
        "color": "bright red",
      }
    }
  },
  "orange": {
    "fruitName": "orange",
    "types": {
      "mandarin": {
        "productCode": "P5",
        "productName": "Mandarin Oranges",
        "color": "orange",
      },
      "bloodOrange": {
        "productCode": "P6",
        "productName": "Blood Orange",
        "color": "red",
      }
    }
  },
}

I am currently designing an Interface structure using Typescript for a project.

My progress so far:

export type FruitTypes = {
  [key: string]: Product,
}

export type Product = {
  productCode: string
  productName: string
  color: string
}

export type Fruits = {
  fruitName: string
  type: object<FruitTypes>
}

The challenge I am facing is how to properly declare the 'type' property in the 'Fruits' interface. type: object<FruitTypes> does not work as expected since it needs to be an object containing objects. How can this be accurately represented in Typescript?

Answer №1

My preferred approach is to utilize the Record<K,T>

export type Fruits = Record<string, FruitTypes>;

export type FruitTypes = {
  fruitName: string;
  types: Record<string, Product>;
}

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}

Alternatively, you can explicitly define it like this:

export type Fruits = {
  [key:string]: FruitTypes;
}

export type FruitTypes = {
  fruitName: string;
  types: {
    [key:string]: Product;
  };
}

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}

This sets Fruits as the overarching type for the structure.

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

Interactive Google Maps using Autocomplete Search Bar

How can I create a dynamic Google map based on Autocomplete Input? Here is the code that I have written: <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDeAtURNzEX26_mLTUlFXYEWW11ZdlYECM&libraries=places&language=en"></scri ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Dropzone is encountering an issue with uploading photos: The upload path seems to be invalid

Despite thoroughly checking the path settings in my code, the error message persists when I attempt to upload photos using Dropzone. It seems to be indicating a problem with the upload path. What could be causing this issue? I am currently in the process ...

Issue with jQuery .on('change') function not functioning correctly following a row being duplicated

Within my input form, I have implemented an on-click function that triggers an ajax call to submit a table row to the database. Upon submission, the row is then duplicated so that the user can input more data if necessary. The issue I am currently facing r ...

Easily move a group of HTML elements at the same time with a simple

Exploring HTML5 Drag and Drop with Multiple Elements When it comes to dragging and dropping multiple elements in HTML5, there seems to be a limitation with the default draggable attribute. This attribute allows only one element to be dragged at a time, ma ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Show a button using CSS when the cursor is hovering

Expressing my gratitude to everyone! I need assistance with implementing a function in reactJS where the <button /> remains hidden during page loading and reveals itself when hovered over. Despite trying various methods, I have been unable to resolve ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...

The value of a Highcharts series does not match that of a Data Source

Encountering an issue with Highcharts where the value of this.y does not reflect the data source. The discrepancy is apparent in the image below. Uncertain if this is a bug or user error. Screenshot illustrating the problem You can view my Demo here: htt ...

Utilize Optional Chaining for verifying null or undefined values

I have utilized the following code: data?.response[0]?.Transaction[0]?.UID; In this scenario, the Transaction key is not present, resulting in the error message: ERROR TypeError: Cannot read properties of undefined (reading '0') Instead of chec ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

Implementing jQuery functionality on elements that are generated dynamically

I'm facing a challenge when working with dynamic elements in jQuery and I really could use some help. Let me provide an example from my current project: main.js $(function () { renderPlaceList(places); setupVoting(); } The two functions are ...

Ways to determine the total amount of days in a given month

As I create a countdown timer, the process involves determining the remaining days in a given month by subtracting the current date from the total number of days in that month. For instance, if there are 30 days in September and 8 days have already passe ...

The v-data-table is unable to fetch the user list information from the API using Axios

How can I solve the issue of displaying "No data available" in the user list data table on my userDirectory page? I have created a userDirectory page with a subheader and a data table from Vuetify, but it seems to have no data available. <template> ...

Utilizing Vue.js for the selection of multiple elements

I am currently in the process of transitioning from jQuery to Vue, and I have encountered an issue when trying to select multiple elements within a single Vue instance. For instance, On my website, there are two posts each with a comment form. I want to ...

Blank area located at the bottom of the document

I'm having trouble designing a webpage without a scroll bar because there isn't much content to display on the page. I've tried searching for solutions and following steps to fix the issue, but I haven't had any success. If anyone can a ...

Adjust dimensions of an image retrieved from a URL

Is there a way to adjust the size of the image displayed here?: var picture = new Image(); picture.src = 'http://www.example.com/images/logo.png'; picture.width = 200; //trying to change the width of the image $('canvas').css({ ...

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...