简体   繁体   English

类型“从不”上不存在

[英]does not exist on type 'never'

Today, I try to write a reducer.ts and got the error inside I define initialstate as below今天,我尝试写一个reducer.ts并在里面得到错误我定义initialstate如下

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

Thank you谢谢

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

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> :如果你不关心打字,你可以将 item 声明为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>;

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:有些人可能会将此称为肮脏的 hack,但是当我有一个通常具有初始构造的接口时,我只是使用一个类来定义初始值并在同一位置键入协定:

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.通过这种方式,您可以在代码中的其他地方根据需要将NameOfMyState作为类型引用,并且您不必单独复制接口和值定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM