首页 > 解决方案 > 在“从不”类型上不存在

问题描述

今天,我尝试写一个reducer.ts并得到了我定义initialstate如下的错误

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

当我在下面得到错误时

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

它声明 item.name 属性 'name' 在 item.name 中的类型 'never'.ts(2339) 上不存在,我知道我应该为 initalstate 创建接口但我不知道该怎么做。任何人都可以建议吗?

谢谢

标签: angulartypescriptngrx

解决方案


您可以为所有必要的接口创建一个文件夹,如下所示:

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
}

然后,在你的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: []
}

推荐阅读