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

Tips for transferring items between two .ts files

Currently, in my code file numberOne.ts, I am making an API call and receiving a response. Now, I want to pass this response over to another file called numberTwo.ts. I have been attempting to figure out how to transfer the API response from numberOne.ts ...

In React, the Textarea component that displays the character count only updates its value after a page reload

Contained within this element is the following component: import React, { useEffect, useState } from 'react'; import { TextareaTestIds } from '../utils/test-ids'; export interface TexareaProps extends React.TextareaHTMLAttributes<H ...

Issue with Angular 5 EventEmitter causing child to parent component emission to result in undefined output

I've been trying to pass a string from a child component to its parent component. Child Component: //imports... @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.c ...

Is there a convenient method for setting up and activating real-time TypeScript checking in Windows 10 using VS Code?

After successfully installing VS Code on my Windows 10 system, I decided to follow the instructions provided here. Upon completion, Node and NPM were also installed correctly. However, I noticed a gap in the setup instructions between installing TypeScrip ...

Verify and retrieve information from the Dynamics CRM Web API with the help of Angular 2 (TypeScript)

How can one authenticate and query the Dynamics CRM Web API from a Single Page Application developed with Angular 2 (TypeScript)? Initial research indicates that: The Dynamics CRM (version 2016 or 365) instance needs to be registered as an application ...

Having trouble with Typescript subtraction yielding unexpected results?

If I have a total amount including VAT and want to separate the net price and the VAT value, how can this be done? For example, if the final price is $80.60 with a VAT rate of 24%, what would be the net price and the VAT value? The correct answer should ...

Attempting to use util.inspect or JSON.stringify on arrays contained within an object does not yield the desired results

My task involves retrieving documents from a MongoDB database using various commands such as find, findOne, findOneAndUpdate, etc. Most of these commands return the entire saved document, which is what I need. However, when utilizing population with find o ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Do we need to duplicate structured data when listing nested objects, or is it better to avoid doing so?

We are currently focused on implementing JSON structured data for a one-page website that contains extensive information about a local business, including address, pricing, reviews, and services. The JSON snippet provided below represents the structured da ...

Troubleshooting the "TypeError: Swiper.initialize is not a function" Issue in React Swiper using TypeScript

Struggling to implement Swiper in a project using nextJs and Typescript. Attempting to modify styles with injectStyle but encountering an error during initialization without knowing how to resolve it. import { useRef, useEffect } from "react"; im ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Tips for making a oneOf field nullable using TypeScript and AJV

A field named platform exists in my code, and it can hold either a string or an array of strings (string[]). The field can also be nullable or undefined if not passed as input. TypeScript Interface export interface IEntityLeaderboardQuery { rank: stri ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

Angular 6: Sending Back HTTP Headers

I have been working on a small Angular Application for educational purposes, where I am utilizing a .net core WebApi to interact with data. One question that has come up involves the consistent use of headers in all Post and Put requests: const headers = ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

Is it possible to determine the type of a class-type instance using class decorators?

Explore this example of faltering: function DecorateClass<T>(instantiate: (...params:any[]) => T){ return (classTarget:T) => { /*...*/ } } @DecorateClass((json:any) => { //This is just an example, the key is to ensure it returns ...

Steps for retrieving JSON data from REST API on on-premise TFS

We are utilizing on-premise TFS Version 15.105.25910.0, also known as TFS 2017, to retrieve JSON data (specifically for a given Work Item id) using Postman for sending/receiving requests. Initially encountered permission denied errors which were resolved ...

What are your thoughts on implementing regular expressions in Zabbix's API

Despite spending hours reading the Zabbix Api documentation, I have not been able to find a way to perform a search by key with multiple possible values. Here is the code I am using: { "jsonrpc": "2.0", "method": "item.get", "params": { "output": "ex ...

`How to Merge Angular Route Parameters?`

In the Angular Material Docs application, path parameters are combined in the following manner: // Combine params from all of the path into a single object. this.params = combineLatest( this._route.pathFromRoot.map(route => route.params) ...