如何在useReducer中将通用类型与必填字段一起使用?

时间:2019-04-07 23:33:47

标签: reactjs typescript

我正在尝试使用useReducer创建一个自定义的React钩子。应该保留对象数组的状态,并且所有对象都必须具有“ id”字段。除id外的对象结构应该是通用的。

这就是我所拥有的;

export enum ArrayActions { INIT, ADD, UPDATE, DELETE }

type ArrayAction<T> =
  | { type: ArrayActions.INIT, payload: T[] }
  | { type: ArrayActions.ADD, payload: T }
  | { type: ArrayActions.UPDATE, payload: T }
  | { type: ArrayActions.DELETE, id: string }

type ObjWithId = { id:any, [key: string]: any }

function arrayReducer<T extends ObjWithId>(state: T[], action: ArrayAction<T>): T[] {
  switch(action.type){
    case ArrayActions.INIT:
      return [...action.payload]
    case ArrayActions.ADD: // TODO: check if id already exists
      return [...state, action.payload]
    case ArrayActions.UPDATE:
      return [...(state.filter(item => item.id !== action.payload.id)), action.payload]
    case ArrayActions.DELETE:
      return state.filter(item => item.id !== action.id)
  }
}

export function useArrayReducer<T extends ObjWithId> (initialState: T[] = []): [T[], React.Dispatch<ArrayAction<T>>] {
  const [state, dispatch] = useReducer(arrayReducer, initialState)
  return [state, dispatch]      // error!
}
最后一行中的

state出现以下错误;

Type 'ObjWithId[]' is not assignable to type 'T[]'.
Type 'ObjWithId' is not assignable to type 'T'.

我认为这可能与ObjWithId的定义有关,但无法完全弄清楚。你能帮我达到想要的结果吗?

1 个答案:

答案 0 :(得分:0)

万一有人需要它;

export interface ListItem { 
  id: string | number | undefined;
  [key: string]: any;
}

export type Action<L extends ListItem> = 
  | { type: "init", items: L[]}
  | { type: "add", item: L }
  | { type: "update", item: L }
  | { type: "delete", id: NonNullable<L["id"]>}