Creating interactive features for a TypeScript interface

I was looking to create a dynamic interface with custom properties, like so:

data: dataInterface [];

this.data = [
  {
    label: {
      text: 'something',
      additionalInfo: 'something'
    }
  },
  {
    bar: {
      text: 'something',
      additionalInfo: 'something'
    }
  },
  {
    whatever: {
      text: 'something',
      additionalInfo: 'something'
    }
  },
];

The labels can be anything and there can be any number of items in the array.

I attempted the following approach:

export interface dataInterface {
  [propName: string]: subDataInterface;
}

interface subDataInterface {
  text: string;
  additionalInfo: string;
}

However, this solution wasn't successful for me. My end goal is to modify the data like this:

this.dataInterface.bar.text = "another example text";

Any suggestions?

Answer №1

Your code structure is on point, but the way you declared your object is incorrect.

Instead of treating test as an array, it should be defined as an object.

const test: testInterface = {
  name: {
    text: "something",
    anotherThing: "something"
  },
  foo: {
    text: "something",
    anotherThing: "something"
  },
  whatever: {
    text: "something",
    anotherThing: "something"
  }
};

this.testInterface.foo.text = "another text for example";

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

Is there a way to retrieve the chosen value from a select element?

How do I retrieve the chosen value from a select element? In my select.component.ts file: export class PfSelectComponent implements OnInit { constructor() { } ngOnInit() { } @Input() options : Array<Object>; } Contents of select.compon ...

Mastering the proper implementation of OneToMany and ManyToOne relationships in MongoDB involves understanding and utilizing the

I am currently working on setting up a oneToMany, ManyToOne relation method and here is my progress so far (pseudocode provided below). I am using Typegoose which is essentially Mongoose with types. If you are unfamiliar with it, that's okay because t ...

The sequence of operations when assigning in Typescript with || and utilizing the array .find method

I need to ensure that the operations in my assignment are happening in a specific sequence. As far as I can tell, it should be following the order listed below. However, I have not been able to locate any documentation on TypeScript that definitively confi ...

Converting a string array to an object leads to an issue where the element implicitly has an 'any' type, as the expression of type 'string' cannot be used to index the type '{}'

Hey there, I have some code that looks like this: export type Options = Record<string, string> export type CheckboxValue<T extends Options> = Partial< Record<keyof T, boolean> > export type Checkbox<T extends Options> = ...

An error occured in angular2: Cannot access the 'title' property of undefined

Here is the code snippet for my custom component: export class MoviedetailComponent implements OnInit { movie:any constructor( private getmovie: GetmovieService, private router: Router, private rout: ActivatedRoute ) { } ngOnInit() { this.r ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...

Refreshing a page in Angular 4/5 using TypeScript

I am currently working on a single-page application that utilizes routes for navigation: this.router.navigate(['/customer-home'], { skipLocationChange: true }); While on the customer home page, I have a feature to add a new customer via a REST ...

Writing Data to Google Cloud Firestore Map using NextJS and Typescript with nested objects

I could use some assistance. I'm developing an application using NextJS (React), TypeScript, and Google Cloud Firestore. Everything seems to be working fine so far. However, I'm facing an issue with storing the address and phone number in a neste ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

The specified type cannot be assigned to the type 'IntrinsicAttributes & MoralisProviderProps'

I'm brand new to TypeScript and I have a question about setting initializeOnMount to true. Why does it only allow me to set it to false? Here is the error message: Type '{ children: Element; appId: string | undefined; serverUrl: string | undefine ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test"> <mat-radio-button *ngFor="let option of options | filter:searchText" class="cssForRow" [value]="option" ...

JavaScript placeholder-type expression

Hey there, I am a C++ developer who is venturing into the world of JavaScript. While exploring JavaScript syntax, I stumbled upon something that resembles templates in C++. For example, while going through RxJs tutorials, I came across this line of code: ...

Can someone please explain how to bring in the Sidebar component?

click here for image description check out this image info An issue arises as the module '@components/Sidebar' or its type declarations cannot be located.ts(2307) Various attempts were made, including: import Sidebar from '@components/Sid ...

Whenever I try to utilize async with React.FC in my React component, a TypeScript error is thrown

I am currently working on a React functional component called DashboardPage that utilizes async/await for fetching data, but I am running into a TypeScript error. The specific error message reads: 'Type '({ params }: DashboardPageProps) => Pro ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...