Typescript method fails to compile due to an indexing error

Imagine you're trying to implement this method in Typescript:

setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) {
  let octdctruns: OctDctRun[] = [...this.octDctRuns];
  const index = octdctruns.findIndex((o) => o.guid === guId);
  octdctruns[index][fieldname] = data;
  this.octDctRuns = octdctruns;
}

The structures UsedTsoClusterKey and OctDctRun are defined as follows:

export interface UsedTsoClusterKey {
  runGUID: string;
  tsoClusterKeyID: string;
  tsoClusterKeyVersion: string;
  validFrom: DateString;
  validUntil: DateString;
}

export interface OctDctRun {
  guid: string;
  moduleType: string;
  runTime: DateString;
  calcIntervalFrom: DateString;
  calcIntervalUntil: DateString;
  triggerType: string;
  triggerID: string;
  usedTSOClusterKeys: UsedTsoClusterKey[];
}

However, an error is occurring at the line octdctruns[index][fieldname] = data:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'OctDctRun'.
  No index signature with a parameter of type 'string' was found on type 'OctDctRun'

If anyone could shed some light on what's going wrong here, it would be greatly appreciated!

Answer №1

When working with Typescript, it's important to note that the compiler might not always recognize fieldName as a property of OctDctRun. Additionally, it may not infer that the value of data is compatible with the specific property you're trying to access using fieldName. Another response offers a solution tailored to your situation, but there's a more versatile approach that doesn't involve hardcoding the data type for data:

class Test {
    setResult<FieldName extends keyof OctDctRun>(guId: string, fieldName: FieldName, data: OctDctRun[FieldName]) {
        let octdctruns = [...this.octDctRuns];
        const index = octdctruns.findIndex((o) => o.guid === guId);
        octdctruns[index][fieldName] = data;
        this.octDctRuns = octdctruns;
    }
}

By utilizing a generic FieldName that must be a key within OctDctRun, specifying that the argument fieldName should correspond to that type, and ensuring that data aligns with that specific fieldName, you can achieve complete type safety at all times.

Feel free to explore this concept further in the TypeScript playground here.

Answer №2

fieldname: keyof OctDctRun - by implementing this solution, you can resolve your current problem. However, there is another issue to consider: the data variable consists of an array of entities belonging to UsedTsoClusterKey. Therefore, it should only be assigned to usedTSOClusterKeys based on your type definition. To adhere to the correct type definition, it should be specified as follows:

keyof Pick<OctDctRun, 'usedTSOClusterKeys'>
. Yet, uncertainty remains whether this adequately addresses your situation ¯\_(ツ)_/¯

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

Incorporating bower packages into Vue.js with webpack

Is there a way to integrate bower components into vue-webpack? I've tried different methods but none seem to work. webpack.base.conf.js http://pastebin.com/Gae193xP Component file <script type="text/babel"> import $ from 'jquery&a ...

Issue with Redux-form's type prop not functioning as expected with checkbox and radio components

Hey there, I'm new to working with redux forms and I've been trying to figure out how to use input types other than "text". I've read through the documentation but for some reason, types like "checkbox" or "radio" are not showing up in the b ...

Submitting a nested JSON object in an AJAX request

When it comes to passing nested JSON through AJAX, the format of the sample request should be like this: { 'user': { 'email': email, 'password': password } } login(){ var email=document.getElementById(& ...

Ensuring the correctness of environment variables in Next.js using Zod

After spending the entire day trying to figure it out, I realize that the solution may be simpler than expected. I am currently using the well-known zod library to validate my environment variables and transform data. However, I keep encountering a persis ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

What could be causing my webpage to freeze every time a filter button is selected?

Tasked with developing a webpage similar to Pinterest by utilizing data from a JSON response. Each JSON object contains a service_name key, which can be manual, twitter, or instagram. I made an effort to implement three filter buttons to only display the r ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...

Is it possible to redirect a URL with a readyState of 4?

Is it possible to redirect to a page when the readyState is equal to 4? //load the send form if (sendRequest) { sendRequest.open("POST", urlRequest, true); sendRequest.setRequestHeader("Content-Type", "application/x-www-form-urlenc ...

What is the best way to uninstall the Google Translation Plugin when transitioning to a new Vue component?

I'm facing a minor issue as I develop a website builder. It consists of two main parts: the builder and the preview section. Within the preview, I've included the Google Translation plugin: onMounted(() => { new google.translate.TranslateEle ...

Tips for arranging TypeScript AST nodes and generating a TypeScript file as the final result

My objective is to reorganize the code in a way that sorts the link(foo) value based on the string text: import Text from '~/text.js' export default function rule(text: Text) { // Sorting rules alphabetically } Although I have made some progr ...

How to convert an attribute of an object within a list to a string separated by commas in TypeScript and Angular

I am working with an array of person objects in Angular 5 and displaying them in HTML using ngFor. The Person objects also contain an array of Role objects. persons:Array<Person>=[]; Each Role object is structured like this: export class Role{ ...

When submitting in an Angular mat-dialog, the page should refresh without closing the dialog

I recently started working with Angular and had to retrieve data from the database to populate a user grid. I successfully completed that task and then moved on to using MatDialog for creating new users. After fixing the creation services and linking them ...

Is it possible to implement websockets with inversify-express-utils?

We are attempting to integrate websockets into our typescript application built on inversify-express-utils, but so far we have had no success: import 'reflect-metadata'; import {interfaces, InversifyExpressServer, TYPE} from 'inversify-expr ...

Acquire a numerical value from a text source and increment it by one using Jquery

I have a simple task of extracting a single number from a particular div. Once obtained, I intend to increment the number by one. However, despite successfully retrieving the number, my attempts to add one to it are not working as expected. For example: ...

Error in Vue.js 2 Composition API: Trying to access 'length' property of undefined object

Greetings to the Vue.js user community! I'm facing a challenging issue that I can't seem to resolve: I am currently using Vue.js 2.x on Windows 11. Whenever I run yarn install or npm install, I encounter an error as displayed in the console. Vi ...

Looking to adjust the API response to fit the necessary JSON format for an Angular project?

A modification is needed in the API response to align with the required JSON format provided below. The current responses and the desired format are detailed for reference. Assistance is appreciated. The current representation of individual's data ne ...

Create a unique V-MODEL for each index that I generate

How can I customize the V-MODEL for each object generated? I am developing a cupcake website where users can create multiple forms with just one submission. However, when generating two fields, the inputs of the second field are linked to the inputs of t ...

Watching for changes to an object's value in an AngularJS service triggered by a controller from a separate module (Extended Edition)

Referring to this discussion on Stack Overflow: AngularJS trigger and watch object value change in service from controller The original question was about watching for changes in a service from a controller. I am interested in extending this concept to ...

Angular 8 template-driven form encountering a Minimum Length Error

Upon clicking the submit button, I encountered the following error: ERROR TypeError: Cannot read property 'minlength' of null I am unsure why this error is happening. How can I go about resolving this issue? Below is the code from app.componen ...

Error: Angular router outlet could not find any matching routes for the requested

I have been working on an application that utilizes lazy-loaded modules for each main section of the app. In one module, I have two router outlets - a primary one and one called details. const routes: Routes = [ { path: '', component: BooksCo ...