Home > Net >  does not exist on type 'never'
does not exist on type 'never'

Time:10-18

Today, I try to write a reducer.ts and got the error inside I define initialstate as below

import { ActionsUnion, ActionTypes } from './actions';
  
export const initialState = {
  items: []  ,
  cart: []
};

while I got the error on below

case ActionTypes.Remove:
      return {
        ...state,
        cart: [...state.cart.filter(item => item.name  !== action.payload.name)]
      };

It state item.name Property 'name' does not exist on type 'never'.ts(2339) in item.name, I know I should create interface for initalstate But I don't know how to do it. Can anyone advise ?

Thank you

CodePudding user response:

You could have a folder for all your necessary interfaces like this:

src/interfaces/item.interface.ts

export interface Item {
  name: string;
  id: number;  // an example
  description: string; // an example
}

src/interfaces/cart.interface.ts

export interface Cart {
  // same here, add the necessary properties
}

And then, in your initialState

import { ActionsUnion, ActionTypes } from './actions';
import { Item } from 'src/interfaces/item';
import { Cart } from 'src/interfaces/cart';

export const State = {
  items: Item[],
  cart: Cart[]
};

export const initialState: State = {
  items: [ {
    name: ''
  }],
  cart: []
}

CodePudding user response:

Some people might call this a dirty hack, but when I have an interface that typically has a initial construction I just use a class to define the initial value and type contract in the same place:

class _NameOfMyState {
    public items: Item[] = []
    public cart: Item[] = []
}
// export the type but not the class
export type NameOfMyState = _NameOfMyState;
export const initialState = new _NameOfMyState();

This way elsewhere in your code you can reference NameOfMyState as a type if needed and you don't have to replicate an interface and value definition seperately.

CodePudding user response:

You have item typed as [], and property 'name' does not exist on this object. If you don’t care about typing, you can declare item as Array<any>:

export const initialState = {
  items: [] as Array<any>,
  cart: []
};

If you want static typing, then you can create an interface for the structure and use it:

export interface item {
name: string;
}

let items: Array<item>;
  • Related