The field 'index' is not found in the type 'Ingredient' in Angular 8

I've been following a tutorial to learn Angular with ngrx and I'm having trouble with my action file.

Here is how my action file looks:

import { Action } from '@ngrx/store';
import { Ingredient } from 'src/app/shared/ingredient.model';

export const ADD_INGREDIENT = 'ADD_INGREDIENT';
export const ADD_INGREDIENTS = 'ADD_INGREDIENTS';
export const UPDATE_INGREDIENT = 'UPDATE_INGREDIENT';
export const DELETE_INGREDIENT = 'DELETE_INGREDIENT';

interface IUpdatePayload {
    index: number;
    ingredient: Ingredient
}

export class AddIngredient implements Action {
    readonly type: string = ADD_INGREDIENT;
    constructor(public payload: Ingredient) {}
}

export class AddIngredients implements Action {
    readonly type: string = ADD_INGREDIENTS;

    constructor(public payload: Ingredient[]) {}
}

export class UpdateIngredient implements Action {
    readonly type: string = UPDATE_INGREDIENT;
    constructor(public payload: {index: number, ingredient: Ingredient}) {}
}

export class DeleteIngredient implements Action {
    readonly type: string = DELETE_INGREDIENT;
    constructor(public payload: number) {}
}


export type ShoppingListActions = 
AddIngredient | 
AddIngredients | 
UpdateIngredient | 
DeleteIngredient;

The reducer file is structured like this:

import { Ingredient } from '../../shared/ingredient.model';
import * as ShoppingListActions from './shopping-list.actions';

const initialState = {
    ingredients: [
        new Ingredient('Apples', 5),
        new Ingredient('Tomatoes', 10),
    ]
};

export function shoppingListReducer(
    state = initialState, 
    action: ShoppingListActions.ShoppingListActions
) {
    switch (action.type) {
        case ShoppingListActions.ADD_INGREDIENT:
            return { 
                ...state, 
                ingredients: [...state.ingredients, action.payload] 
            };
        case ShoppingListActions.ADD_INGREDIENTS:
            return {
                ...state,
                ingredients: [...state.ingredients, ...action.payload]
            }
        case ShoppingListActions.UPDATE_INGREDIENT:
            const ingredient = state.ingredients[action.payload.index];
            const updatedIngredient = {
                ...ingredient,
                ...action.payload.ingredient
            }
            return {
                ...state,
                ingredients: [...state.ingredients]
            };
        case ShoppingListActions.DELETE_INGREDIENT:
            return {};
        default: return state
    }
}

I encountered an error in the line

case ShoppingListActions.UPDATE_INGREDIENT:
specifically at action.payload.index, stating that
Property 'index' does not exist on type 'Ingredient | { index: number; ingredient: Ingredient; }'.
  Property 'index' does not exist on type 'Ingredient'.

I'm unsure of what I might be doing wrong. Any assistance would be greatly appreciated. Thank you

Answer №1

Within your action file, specifically in the initial export class declaration, it is necessary to modify

readonly type: string = ADD_INGREDIENT;

to

readonly type = ADD_INGREDIENT;

Answer №2

Revise this

readonly type: string = ADD_INGREDIENT;

into

readonly type = ADD_INGREDIENT;

however, the issue persisted until I eliminated the string type for all classes in the action file.

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

What is the best way to handle arithmetic operations with multiple input fields in Angular?

In my form, users input number values which I need to send to my ts file for multiplication when a button is clicked. View screenshot example Below are the code snippets: calculate(value0,value1){ this.bindData(value0,value1); } bindData(a,b){ ...

What is the best way to create a search box in AngularTS?

My search box code is not functioning properly. Can someone please assist me in fixing it? html: <form #f="ngForm" (ngSubmit)="onSubmit(f)" #searchForm="ngForm"> <input type="search" placeholder="Search..."> </form> search-form Compo ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

What is the best way to retrieve all keys from a deeply nested object using recursion

type NestedObject = { amount: number, error: string | null, data: { rows: [], messages: { goodNews: string | null, badNews: string | null } } } //attempting to recursively retrieve all keys type AllKeys<T, K extends keyof T> = T e ...

Custom Email Template for Inviting Msgraph Users

I'm currently exploring the possibility of creating an email template for the MS Graph API. I am inviting users to join my Azure platform, but the default email they receive is not very visually appealing. public async sendUserInvite(body: {email: < ...

Typescript/Three.js encounters the issue of game objects becoming undefined

Something in my code seems to have broken unexpectedly. I can't figure out why the "Game" object is defined before calling this.render() in the constructor, but becomes undefined in the render method. Before render(), the console shows: Game camera: ...

In Angular, additional code blocks are executed following the subscription

I am facing an issue with my file upload function. After the file is uploaded, it returns the uploaded path which I then pass to a TinyURL function this.tinyUrl.shorten(data.url).subscribe(sUrl => { shortUrl=sUrl;});. However, there is a delay in receiv ...

Tips for transferring data between functions in component.ts in Angular 2

When I click a button, I am passing some values using "data.someid" and I want to retrieve this value in another button click. html --- <button (click)="click1(data.someid)"></button> <button (click)="click2()"></button> In my com ...

Error Encountered: Unable to locate angular/core module in Angular 2

I have encountered an issue while setting up a new Angular2 app from the quickstart folder on the Angular website. Despite following all suggested solutions, I am still facing errors. After running npm install, everything seems fine as I can see my node_mo ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Verify that the password is entered correctly in Angular2

My Angular2 form looks like this: this.registerForm = formBuilder.group({ 'name': ['', Validators.required], 'email': ['', Validators.compose([Validators.pattern("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+&bso ...

Generate a fresh JSON object by adjusting JSON data in Angular 6

Here is a sample JSON structure: [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx" } }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx" } ] I need to split the values of the K ...

Using HttpClient delete method to send a body in Angular 5

While transitioning from Http to HttpClient in my Angular 5 application, I encountered a roadblock when working on a specific method within one of the services: deleteMultipleObjects(userId: number, officeId : number, objectsData : any) { const url = `$ ...

Error encountered in Jest while searching for entities using the class: TypeORM RepositoryNotFoundError

Recently, I encountered a puzzling issue that has been quite challenging to debug. After upgrading all the project dependencies, my tests (using Jest 25.5.4 or 26.x) started failing with the dreaded "RepositoryNotFoundError." The peculiar thing is that al ...

Is there a way to implement depth-first retrieval in rxjs using the expand method?

Currently, I am engaged in a project utilizing Angular 7, Typescript, and RxJS 6.3.3. In this project, I am working with RxJS Observables and relevant operators to handle hierarchical collections of objects obtained from an http server that interfaces with ...

Images appear as plain text in the preview of VUE 3 (with TypeScript)

Currently, I am developing a Portfolio website and have encountered an issue. While everything runs smoothly with npm run dev, the problem arises when I use npm run preview. In this scenario, some of the images within the files named 3dModellingFiles.ts do ...

Firestore real-time document listener disrupts sorting functionality

I've encountered a Firestore problem that I'm hoping the community can assist me with. It seems that my active document snapshot listener is causing issues with sorting behavior, and I'm struggling to understand why. Upon initializing my c ...

There seems to be a mismatch in this Typescript function overloading - None of the over

Currently, I am in the process of developing a function that invokes another function with enums as accepted parameters. The return type from this function varies depending on the value passed. Both the function being called (b) and the calling function (a ...

The Vue property I customized in my component is not being recognized by VSCode(Vetur)

I've successfully implemented a plugin in Vue by declaring it in a main.ts file, defining its type in a plugin.d.ts file, and utilizing it in a component.vue file. Although the compilation is error-free, I am encountering an issue with VSCode intellis ...

Protector of the young travelers' paths

I have encountered a recurring issue with implementing Guards on my pages. Despite referencing multiple solutions from StackOverflow, none of them seem to work for me. Take this example for instance. This is my first attempt at restricting access to cert ...