Encountering a Typescript issue while dynamically modifying an object's property

Having difficulties updating an Object's property based on a dynamic variable. Even after searching for answers on stackoverflow, I haven't been able to find a solution.

export interface Bikes {
  totals: Array<number>;
}

interface Products {
  cars:  Cars;
  bikes:  Bikes;
}

export interface RawData {
    products: Products
}

demo( data: RawData ) {
  // data.products contains both "cars" and "bikes" properties.
  for (var type in data.products) { 
    for (var product in data.products[type].totals) {// <-- error here
                        -------------
     ....
   }
}

An issue arises - "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Products'. No index signature with a parameter of type 'string' was found on type 'Products'."

Attempted using:

export interface RawData {
    products: keyof Products
}

But then received an error on data.products[type].totals

Error message: "Property 'bikes' does not exist on type 'string'."

Answer №1

The variable type in your situation is deduced to be of type string.

TypeScript does not allow you to use the string type as an index for the RawData['products'] type.

If you want to convince TypeScript that it is possible, you have two options:

1) Employ type assertion

function demo(data: RawData) {
  for (const type in data.products) {
    // explicitly define the type for the `type` variable
    for (const product in data.products[type as keyof RawData['products']]) { // okay

    }
  }
}

2) Make Products indexable

interface Products {
  cars: Cars;
  bikes: Bikes;
  [prop: string]: Cars | Bikes
}

UPDATE

interface Bikes {
  totals: Array<number>;
}

type Mix = { foo: 'a' };

type Products = {
  cars: Cars;
  bikes: Bikes;
  mix?: Mix;
}
type Values<T> = T[keyof T]

type MakeIndexed<T> = T & { [prop: string]: Values<T> }


interface RawData {
  products: MakeIndexed<Products>
}

function demo(data: RawData) {
  for (const type in data.products) {
    for (const product in data.products[type]) { // okay

    }
  }
}

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

I'm experiencing issues with my GAS script when trying to generate events, as it is unable to

Issue After creating a script to generate events from specific emails, the script runs without errors but does not display any events on the calendar. I am confident in the code itself and suspect that there may be authentication settings needing configur ...

Angular 2 Ahead-of-Time compiler: all clear on the error front, yet a nagging feeling of

I've spent the last 72 hours trying to figure out how to make Ahead-of-Time compilation work for my Angular 2 rc.6 application. Currently, my application runs smoothly using Just-in-Time compilation. I've made sure to install all necessary depe ...

A guide on displaying data from objects containing arrays in React using TypeScript

Hey there! I'm currently facing a challenge in rendering values within an object containing arrays. Let me show you an example of the object structure: data { info1: [{note: "this is note 1", status: true}], info2: [{note: "this i ...

What is the process of programmatically sorting a column in a Material UI DataGrid?

Hey there! I'm currently working on a DataGrid that has a column with a custom header, specifically a Select option. My goal is to have the column sorted in descending order every time a user selects an option from the dropdown menu. renderHeader: (pa ...

Deployment of Typescript.js files in Angular 2

Do you think it's practical to gulp-typescript the typescript files into js files for deploying on a webserver, considering that the Angular2 quickstart guide requires a typescript-1.x.x.js file that is around 2.9MB in size, even when minified? ...

Exploring the capabilities of Web MIDI in the context of Angular

I am a beginner with Typescript and I am currently working on using Angular2 to develop a Web Midi application. However, I am facing some difficulties in understanding certain errors that I encounter. I believe that I should be placing the Midi functions w ...

error TS5023: Compiler option 'enableIvy' is not recognized

I recently attempted to integrate IVY into my angular 7 beta project. To do this, I included enableIvy: true in the compilerOptions section of src/tsconfig.app.json. However, upon running ng build --prod --aot --output-hashing none, an error was encounter ...

Can the string literal type be implemented in an object interface?

My custom type is called Color, type Color = 'yellow' | 'red' | 'orange' In addition, I created an object with the interface named ColorSetting. interface ColorSetting { id: string yellow?: boolean red?: boolean orang ...

The utilization of `ngSwitch` in Angular for managing and displaying

I am brand new to Angular and I'm attempting to implement Form Validation within a SwitchCase scenario. In the SwitchCase 0, there is a form that I want to submit while simultaneously transitioning the view to SwitchCase 1. The Form Validation is fun ...

Transform ECMAScript Observable / Zen Observable into RXJS Observable

I currently have an ECMAScript Observable that is compliant with specifications, specifically sourced from the wonka library. I am facing challenges in converting this type of observable to an rxjs 6 observable. It appears that this conversion was possibl ...

Enhance your TypeScript skills by leveraging types on the call() method in redux-saga

Is there a way to specify the types of a function using call()? Consider this function: export function apiFetch<T>(url: string): Promise<T> { return fetch(url).then(response => { if (!response.ok) throw new Error(r ...

How can you avoid inspecting webpack internal code when debugging in Visual Studio Code with React Typescript or NextJS?

While debugging NextJS Typescript, the Visual Studio Code debugger seems to be stepping into webpack-internal generated source files. The launch.json file in Visual Studio code is configured as: { "version": "0.2.0", "configura ...

Variables in Angular DI become undefined when a method is called through a passed function reference

Utilizing Angular, I have a class with several Dependency Injection (DI) variables. During normal execution of a method within the class, everything functions as expected and I can access the injected instances of the DI variables. Now, my goal is to crea ...

Changing the names of properties within a intricate JSON structure

I have a JSON data structure that is quite complex, like the one shown below: const json = '{"desc":"zzz", "details": { "id": 1, "name": "abc", "categoryDetails": { "cid": ...

Sending Functions as Props in React Using Typescript from a Parent Component to a Child Component

Trying to pass props from Parent to Child using TypeScript-React but getting an error: "Type 'void' is not assignable to type 'Function'." Parent import React from "react"; import Navbar from "./navbar"; import Main from "./main"; f ...

Jest ran into a surprising token related to NUXT typescript

After spending two days searching and trying various solutions without success, I am reaching out for help. Can anyone provide a clue? Below are the configuration files I am using. Any assistance would be greatly appreciated. jest.config.js .babelrc .babe ...

Instructions for setting 0 as a valid value in Html code and displaying it

I have a query regarding HTML code within an Angular app. My inquiry is, is there an alternative method to check for null or undefined values in an ngIf statement? The code I am working with looks like this: <div ngif= "value !== null and value ! ...

Unable to set a value to a TypeScript object mapping

I encountered an issue with my typescript dictionary. Whenever I try to assign a value to it, a specific error occurs. TypeError: Cannot set property 'v1/items/someItemType/someItemId/EVENT/some DataTypeId' of undefined at ...

Are angular route guards reliable for ensuring security?

As I develop my online store, I have created an administration section that allows users to track and make modifications to orders. This area is securely protected by authentication measures including password hashing on a node server. However, my concer ...

The service remains operational while the button's status undergoes a change

In my data table, each row has a column containing buttons. To ensure that only the button in the clicked row is executed, I include the index of that row in the start/pause timer function. I decided to create these functions in a service so that the time ...