What is the best method for transforming an object into an interface without prior knowledge of the keys

I am looking for a solution to convert a JSON into a TypeScript object. Here is an example of the JSON data:

{
  "key1": {
    "a": "b"
  },
  "key2": {
    "a": "c"
  }
}

The keys key1 and key2 are unknown, so I cannot directly create an interface for them. However, the objects associated with these keys are always the same.

Currently, I have defined my object as follows:

export interface MyObj {
  a: string;
}

But how can I convert the JSON into an object? I attempted to use a map object type like this:

export interface AllMyObj {
  valKey: Map<string, MyObj>;
}

However, I am unsure what should be used in place of valKey.

Answer №1

Your interface should expand to Record<string, MyObj> (TS playground):

export interface MyObj {
  a: string;
}

interface AllMyObj extends Record<string, MyObj>{}

Alternatively, you can simply use it as a type (TS playground):

export interface MyObj {
  a: string;
}

type AllMyObj = Record<string, MyObj>

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

Parsing PHP JSON data into variables

I'm facing an issue with my JSON data. I am sending it through C# and receiving it on my PHP MySQL server. Normally, I catch the data using POST method but now I realize I should use json_decode instead. Even though I can see and print out the data, I ...

Creating variables in Typescript

I'm puzzled by the variable declaration within an Angular component and I'd like to understand why we declare it in the following way: export class AppComponent { serverElements = []; newServerName = ''; newServerContent = &apos ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

Sending data to and retrieving data from a server

Just a quick query. I've been using ajax POST and GET methods to send JSON data to a server and then fetch it back. However, I'm facing some confusion while trying to extract JSON information from the GET call. getMessage = function(){ $.ajax ...

Template7 produces a bizarre outcome referred to as "each this" whenever JSON is utilized

Currently, I am experimenting with dynamically loading content on Framework7/Template7 pages. Everything works perfectly fine when using static "context" in JSON format. However, when attempting to test it with real-world data from an API, I encounter a st ...

IE8 is encountering a null JSON response from the HTTP handler, unlike IE10 and Chrome which are not experiencing this

Here is my JavaScript code snippet: patients.prototype.GetPatient = function(patient_id,callback) { var xmlhttp; var fullpath; try { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { ...

Save the ID values of selected users in Angular Mentions feature

Using the angular mentions library, I successfully incorporated a textarea that enables me to mention multiple users. Is there a method to store the IDs of the selected users? Ideally, I would like to save them as an array of strings. For instance: If I ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...

Using PHP's foreach loop to iterate through an array and generate a JSON file

Apologies for my lack of experience in this area. I am aiming to generate the following JSON structure: "commodities": [ { "originCountryCode": "NL", "goodsDescription": "Commodity goods des ...

Next.js does not recognize Typescript Context

I encountered an unexpected custom error while trying to implement custom error notifications in my form. The custom context I set up for this functionality does not seem to be working as intended, resulting in a thrown error for its non-existence. My deve ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...

Original: Generic for type guard functionRewritten: Universal

I have successfully created a function that filters a list of two types into two separate lists of unique type using hardcoded types: interface TypeA { kind: 'typeA'; } interface TypeB { kind: 'typeB'; } filterMixedList(mixedList$: ...

Tips on how to effectively unit test error scenarios when creating a DOM element using Angular

I designed a feature to insert a canonical tag. Here is the code for the feature: createLinkForCanonicalURL(tagData) { try { if (!tagData) { return; } const link: HTMLLinkElement = this.dom.createElement('link'); ...

"Implementing self-referencing mongoose models in Typescript: A step-by-step guide

I have a model: const message = new mongoose.Schema({ id: { type: ObjectId, required: true }, text: { type: String }, replies: [message] }); Looking to create a document structure like this: { "id": 1, "text": "Main Message", "replies": [ ...

How can we use tsyringe (a dependency injection library) to resolve classes with dependencies?

I seem to be struggling with understanding how TSyringe handles classes with dependencies. To illustrate my issue, I have created a simple example. In my index.tsx file, following the documentation, I import reflect-metadata. When injecting a singleton cl ...

Navigating to a specific div within a container with vertical overflow in an Angular application

I am working on an angular application where I have a left column with a scrollable div that has overflow-y: auto;, and a right column with bookmark links that jump to sections within the scrollable container. I am currently facing two challenges: 1 - Co ...

Creating an Angular component to display a dynamic table using ngFor directive for a nested JSON data structure

Currently diving into Angular (version 8) and grappling with the following JSON structure {layer1 : [ { id: 'lay1', name: 'first layer', results: [ { rows: ...

Parsing JSON data repeatedly using JavaScript within an HTML environment

The following code I found on a popular web development website works perfectly: <!DOCTYPE html> <html> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...