How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly:

export interface Content {
    categories: string[]
    concepts: Topic[]
    formulas: Topic[]
    guides: Topic[]
}

//this.content is of type Content
['formulas', 'concepts'].forEach(c => {
      this.content[c].forEach(topic => {
//....
      });
    })

However, it now triggers an error (For the line this.content[c]):

An 'any' type is implicitly related to 'Element' because an expression of type 'string' cannot be used to index type 'Content'. No index signature with a parameter of type 'string' was found on type 'Content'.ts(7053)

How can I inform Typescript that this.content[c] is an array containing instances of Topic?

Answer №1

Implement it in this manner:

['methods', 'theories'].forEach(m => {
    this.data[m as keyof Data].forEach(item => {
        //....
    });
})

Answer №2

After considering various options, I made a final decision on the design:

interface DataContainer {
    types: string[]
    topicsByType: Data
}

interface Data {
    [categoryKey: string]: Topic[]
}

This adjustment ensures that every string key corresponds to an array of Topic objects.

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

Error: Browserify jQuery Plugin Not Working

Having trouble browserifying a jQuery plugin and keep seeing this error in the browsers console: Uncaught Error: Cannot find module 'jquery' Here's how I have my package.json set up: "browserify": { "transform": [ "browserify-shim" ...

Push the accordion tab upwards towards the top of the browser

I am working on an accordion menu that contains lengthy content. To improve user experience, I want to implement a slide effect when the accordion content is opened. Currently, when the first two menu items are opened, the content of the last item is disp ...

Determine the size of an SVG while taking into consideration any strokes applied

Is there a way to seamlessly position an SVG in the corner of a div, despite having a dynamically generated stroke? Calculating the distance to the outermost part of the border proves difficult when dealing with irregular shapes like stars. Here's my ...

Tips for bringing in pictures from outside directories in react

I am new to React and trying to import an image from a location outside of the project's root folder. I understand that I can store images in the public folder and easily import them, but I specifically want to import them from directories outside of ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

The missing binding.node file is causing an issue with Node-sass

Previously, my angular project 7.1 was running smoothly until I upgraded to ubuntu 19.10 and encountered an error upon running npm install: > [email protected] install /home/gabb/dev/homepage/node_modules/node-sass > node scripts/install.js Do ...

Next JS now includes the option to add the async attribute when generating a list of script files

We are currently working on a nextJs application and are looking to add asynchronous functionality to all existing script tags. Despite numerous attempts, we haven't been successful in achieving this. Can anyone provide some guidance or assistance? &l ...

Using the .ajax() function with jQuery to retrieve data and then using .find() on that data

Currently I am facing an issue while trying to extract the body tag from the result of the .ajax() call. Instead of getting the desired result, I only see undefined logged into the console... This is the section of code causing the problem: $(document).r ...

Canvas drawImage function not displaying image at specified dimensions

I'm having trouble loading an image into a canvas using the drawImage function. Additionally, I've implemented drag functionality but found that when moving the image inside the canvas, it doesn't follow the mouse cursor in a linear manner. ...

Change the size of the font with a slider in VueJS

I have been utilizing the project found at This particular project allows end-users to reuse Vue components as editable sections by providing a styler overlay for adjusting content within a div or section. After installation, I added a slider which now ap ...

The button I have controls two spans with distinct identifiers

When I press the player 1 button, it changes the score for both players. I also attempted to target p2display with querySelector("#p2Display"), but it seems to be recognized as a nodeList rather than an element. var p1button = document.querySelector("# ...

Leveraging the callback function to display information from a JSON file

Attempting to retrieve JSON data from a PHP file and display it. Managed to successfully request the data via AJAX and log it to the console. (At least one part is working). Tried implementing a callback to ensure that the script waits for the data befor ...

What sets apart `var now = new Date();` and `var now = Date();` in JavaScript

I am specifically interested in exploring the impact of adding "new" on the variable, as well as understanding when and why it is used. I would also like to understand why I am obtaining identical answers when printing both versions. ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Is there a way to compare two regex values using vuelidate?

Can someone assist me with validating an input field using vuelidate? I am looking to return a valid result if either of the two regular expressions provided below is true. const val1 = helpers.regex('val1', /^\D*7(\D*\d){12}\ ...

Executing various angular 4 applications simultaneously using a shared Node.js server for rendering purposes

What is the best way to configure index files for both front-end (Angular 4 CLI) and backend (Angular 4 CLI) in order to manage two separate Angular apps? ...

Creating a bezel design in CSS or Vue: A step-by-step guide

Embedding: Is there a CSS property that can be used to create the same angle as shown in the layout? I looked everywhere in the program but couldn't find this specific property. Tried searching here !: ...

What is preventing me from accessing the $sceProvider?

Struggling to implement a filter using $sceProvider to decode HTML tags. Here's my current code structure: myApp.filter('decodeHtml', function($sce) { return function(item) { return $sce.trustAsHtml(item); }; However, upon integrating ...

Is it possible for using str_replace('<') to protect against code injected by users?

Recently, I've been working on a script that involves user input. In this script, I use echo str_replace('<', '&lt;', str_replace('&','&amp;',$_POST['input']));. It seemed like a solid f ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...