In TypeScript, create an object with a set number of key-value pairs, denoted

As a newcomer to Typescript, I want to create interfaces for the JSON data shown below:

{  
   "company":"abc inc",
   "logoUrl":"someUrl",
   "phone":"1234567890",
   "branch":{  
      "nyc":{  
         "products":{  
            "asian":{  
               "somekey1":"someValue1",
               "somekey2":"someValue2",
               "somekeyN":"somevalueN"
            },
            "american":{  
               "somekey1":"someValue1",
               "somekey2":"someValue2",
               "somekeyN":"somevalueN"
            }
         }
      },
      "boston":{  
         "products":{  
            "asian":{  
               "somekey1":"somevalue1",
               "somekey2":"somevalue2",
               "somekeyN":"somevalueN"
            },
            "american":{  
               "somekey1":"somevalue1",
               "somekey2":"somevalue2",
               "somekeyN":"somevalueN"
            }
         }
      }
   }
}

I have defined interfaces for this structure, but I am stuck on how to properly define the asian and american objects with multiple key-value pairs. Can someone provide guidance on the correct syntax for this? Your help is much appreciated. Thank you.

interface Products {
    asian: {};
    american: {};
}

interface Configuration {
    company: string;
    phone: string;
    logoUrl: string
    branch: {
      nyc: {
        products: Products;
      };
      boston: {
         products: Products;
      };
    };
}

Answer №1

declaration Products {
    asian: {[key: string]: string};
    american: {[key: string]: string};
}

In this scenario, I am specifying to typescript that the 'asian' attribute is a map where the key and value are both strings.

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

I am looking to display the dynamic response in Angular8 in real-time

Looking for ways to dynamically bind JSON data to HTML page elements like labels and textboxes using Angular. Any insights or recommendations are welcome. { "model": "abcd.abilivcdcty.configuration", "typeId": "abcd.edge.modules.opcuamodule. ...

SyntaxError: JSON parsing error - encountered an unexpected character at the beginning

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); const fs = require("fs"); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // http://expressjs.com/en/starter/static-files ...

How can I limit a type parameter to only be a specific subset of another type in TypeScript?

In my app, I define a type that includes all the services available, as shown below: type Services = { service0: () => string; service1: () => string; } Now, I want to create a function that can accept a type which is a subset of the Service ...

What is causing the .responseToString function to be recognized as not a function?

Consider the following scenario with Typescript: interface IResponse { responseToString(): string; } export default IResponse; We have two classes that implement this interface, namely RestResponse and HTMLResponse: import IResponse from "./IRespo ...

Retrieving precise object values with jQuery Ajax

I'm currently utilizing a dictionary REST API through Ajax. $.ajax({ url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1", dataType : 'json', success: fun ...

Converting multiple JSON entities into a DataFrame

I am in possession of numerous JSON files, each containing structured data across various entities as shown below: { "block": { // Block data details }, "transactions": [ { // Transaction data details } ], &q ...

Transform a nested JSON Object into a customized array structure

My task involves converting a nested JSON object into a specific format, as demonstrated below: let jsonObj ={"data": { "cardShop": { "cardData": { "cardTitle": "The Platinum Card<sup> ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

Search for URLs using both www and non-www, as well as both http and https, with the jQuery.g

I am currently using jQuery to search through a JSON string in order to find the matching URL and extract all data associated with that object. The URL is fetched using var url = window.location.href; However, this returns Within the JSON string, the U ...

Test your knowledge with this quiz on Typescript's AddOrSubtract functions

Just starting out with learning Typescript and tackling this challenge from Execute Program: Create a function that either adds or subtracts 1 from a given number. The first argument is the number, and the second argument is a boolean. If the boolean is ...

Issue occurred: Unable to locate metadata.json file while attempting to push to openShift git

I encountered an issue while trying to deploy a second version of my nodeJS + MongoDB app on OpenShift. The initial deployment was successful, but the subsequent attempt is failing with the following error message: Erics-MacBook-Air:rippleRating ericg$ gi ...

Rest-Assured encounters difficulty validating the response of a JSON array

I'm currently working on validating the presence of a specific value in a JSON array using Rest-Assured and hamcrest matchers in Java. Below is the JSON structure that I need to validate: { "graph": { "groupedResultColumns": [ ...

Prevent the editor window from closing when you close the final tab in VS Code

When there is only one tab open in an editor in VS Code, the default action is to close the editor immediately. Many people find this behavior frustrating as they would prefer to keep their workspace layout intact. Is there a way to change this setting? ...

Developing a unique style.css for WordPress using package.json and Gulp

My experience with Gulp is fairly new, but I've been using it to streamline my build process for developing WordPress themes. I have successfully configured my package.json file and now I want my style.css file to dynamically reflect the version speci ...

Combining Three Functions into One

Is it possible to merge these 3 functions together for a seamless data stream display in individual divs? How should I approach this? The AJAX request does not retrieve the users' first, middle, or last names under response.users but rather response. ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

The outcome of Express.json() is void

I'm struggling with the functionality of express.json() in my code. Despite researching extensively both here and online, I haven't been able to find a solution. Here is the code snippet: app.use(morgan("dev")); app.use(cors()); app.use(helmet() ...

What is the best way to extract a value from a Json in C# using .NET 3.5?

When working with .NET 4.5, I found a solution with the following code: string respString= response.Body; // { "name":"John", "age":30, "car":null} var respObj= JsonConvert.DeserializeObject<dynamic>(respString ...

What is the best way to eliminate quotation marks surrounding a boolean value within a JSON string?

The current string is: String example = {"test":"true"} However, I would like it to be in this format: example = {"test":true} Is there a way to convert the initial string to match the desired format? ...

The service has terminated unexpectedly because of signal: Ended prematurely: 9

I'm encountering the error 'Service exited due to signal: Killed: 9' and am unable to launch my app. I've come across information suggesting that this may be caused by memory leaks or a lengthy startup time for the app. In all honesty, ...