The creation of a parameterized function that doubles as an object property

interface item {
  first: string;
  last: string;
}

const itemList = Item[];

updateAttribute = (index, attributeToUpdate) => {
  itemList[index].attributeToUpdate = "New first/last"
}

The snippet above showcases an interface named item with properties first and last. There is also an array called itemList, specifically containing objects of type item.

An attempt was made to create a function that takes an index from the array and a string called attributeToUpdate, which could be either first or last.

However, this implementation led to a TypeScript error stating 'Property 'attributeToUpdate' does not exist on type 'item'.' What would be the best approach to tackle this issue?

Answer №1

To change the attribute value for a specific index in the array, you can use the following code:

arr[index][attributeToChange] = "New first/last"

Make sure to declare the type annotation on the left-hand side like this:

const arr: item[] = [];


Update: If you received an error message from the TypeScript compiler stating

[ts] Element implicitly has an 'any' type because type 'item' has no index signature.
, you will need to define an index signature in the interface. By specifying the key types and value types within the item interface, it will eliminate any warnings about implicit types.

interface item {
  [key: string]: string;
  first: string;
  last: string;
}

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

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

Issue: unable to establish a connection to 127.0.0.1:465 to send an email

When attempting to send smtp alert messages from my site's email account <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55363a3b2134362115383a3b263c21307b363">[email protected]</a> to the email addresses of m ...

Nested promises utilized within functional programming techniques

Working on an Angular project involves developing a booking system with various scenarios. The challenge lies in handling different server calls based on the response of a promise, leading to a nested callback structure that contradicts the purpose of prom ...

Improving the efficiency of AES decryption in Node.js

I had the idea to build a webpage that would display decrypted data fetched from the server. The app.js file on the server reads and decrypts all the data from a specific folder. var http = require('http'); var path = require('path'); ...

Tips for avoiding an endless loop in my React code while utilizing setState within useEffect

Make sure to view the code on codesandbox at this link: https://codesandbox.io/s/bold-hamilton-k1nzs When I execute the code, it triggers an endless loop, causing the entries to grow rapidly. Eventually, the website crashes due to this issue. The state v ...

Limited achievements seen with AJAX. Occasionally, either no data is retrieved or an error is encountered

My experience with AJAX has been frustrating so far. I am trying to populate some textboxes with values from a database, but nothing is getting inserted. The only thing that's happening is the appearance of two errors related to specific values which ...

Is AGM-Map capable of providing all the same features as the Google Maps API?

Greetings to everyone! I am currently working on an Angular 6 project and I want to incorporate asset tracking using the Google Maps API. However, I am unsure if AGM-Map fully supports all the features of Google Maps API, like heatmaps and advanced asset ...

The property X within the ClassB type cannot be assigned to the identical property within the parent type ClassA

I deal with the following set of Typescript classes: Firstly, we have an abstract class export abstract class MyAbstractClass { ... } Next is Class A which implements the methods from the abstract class export ClassA extends MyAbstractClass { ...

What is the process for adding an image to a scene using menu options?

I'm looking for assistance in loading an image into a scene upon clicking a menu option. Any guidance would be greatly appreciated. Please let me know if more information is required. Here's the method I've tried, which involves testing a v ...

What could be causing the Material UI tabs to malfunction when dynamically populating the content using a .map function instead of manually inserting it?

I was able to successfully integrate Material UI's tabs by manually adding content, but when I attempted to use a .map function to populate the content from a JSON data source, it stopped working. Can someone help me figure out why? The only change I ...

Error: The value of _This.props is not defined

Hey there, I am new to working with React Native and could really use some assistance with this issue: TypeError: _props.goToScreen is not a function. Any help would be greatly appreciated, thank you in advance! In my Profile.js file, I am trying to click ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

I want to create a feature in Angular where a specific header becomes sticky based on the user's scroll position on the

When working with Angular, I am faced with the challenge of making a panel header sticky based on the user's scroll position on the page. I have identified two potential solutions for achieving this functionality. One involves using pure CSS with pos ...

Transform a string (variable) into an object using JSON.parse, encountering an unexpected token error

I am struggling with parsing a string variable back to an object. Despite searching through various posts on this issue, I have not found a solution that works for me. if(subMatch.match(/\{.*\}/)){ /// new Object of some sort var o ...

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

Invoke Javascript through CSS selector

On my webpage, I have implemented a mousemove-mask feature that was inspired by an existing codepen. However, there is one significant issue that I can't seem to resolve on my own. Despite my attempts to fix it, I believe someone with more expertise c ...

Challenges with Cross-Origin Resource Sharing (CORS) when accessing Uber API OAuth

I am encountering an issue while attempting to make client-side JS calls to Uber API endpoints that require the OAuth Bearer token, such as /v1/me. The problem arises due to the absence of the Access-Control-Allow-Origin header in the response. I have suc ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

If I type too quickly in the input field, it ends up displaying the incorrect div

I need to display two different dropdowns in my input field. To achieve this, I am using a method called shouldShowWarningBox that gets triggered every time the user updates the input and updates the value of showWarningBox accordingly. However, when I typ ...