'never' 类型不存在

does not exist on type 'never'

今天尝试写一个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' 在类型 'never' 上不存在 'never'.ts(2339) 在 item.name 中,我知道我应该为 initalstate 创建接口 但我不知道该怎么做。 任何人都可以建议吗?

谢谢

您可以像这样为所有必要的界面创建一个文件夹:

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: []
}

您的项目类型为 [],而 属性 'name' 在此对象上不存在。如果你不关心打字,你可以将项目声明为 Array<any>:

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

如果你想要静态类型,那么你可以为结构创建一个接口并使用它:

export interface item {
name: string;
}

let items: Array<item>;

有些人可能会称之为肮脏的 hack,但是当我有一个通常具有初始构造的接口时,我只是使用 class 在同一个地方定义初始值和类型契约:

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

这样,如果需要,您可以在代码的其他地方引用 NameOfMyState 作为类型,而不必单独复制接口和值定义。