今天,我嘗試寫一個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 創建介面但我不知道該怎么做。任何人都可以建議嗎?
謝謝
uj5u.com熱心網友回復:
您可以為所有必需的介面創建一個檔案夾,如下所示:
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: []
}
uj5u.com熱心網友回復:
有些人可能會將此稱為骯臟的 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();
通過這種方式,您可以在代碼中的其他地方NameOfMyState根據需要將其參考為型別,而不必單獨復制介面和值定義。
uj5u.com熱心網友回復:
您已將專案鍵入為 [],并且此物件上不存在屬性“名稱”。如果您不關心打字,您可以將 item 宣告為Array<any>:
export const initialState = {
items: [] as Array<any>,
cart: []
};
如果你想要靜態型別,那么你可以為結構創建一個介面并使用它:
export interface item {
name: string;
}
let items: Array<item>;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/322492.html
上一篇:c語言的階乘程式
