在Redux Toolkit中将State与HTMLElement一起用于createSlice

时间:2020-08-20 02:40:42

标签: redux-toolkit

尝试创建一个化简器,其状态包含一个HTMLDivElement类型的键(或任何其他HTMLElement派生类)时,对于似乎是HTMLElement的所有键,我得到了一个Argument of type '...' is not assignable to parameter of type

interface ITestEvent {
  name: string;
  id: string;
  ref: HTMLDivElement;
}

interface AddEventPayload {
  event: ITestEvent;
}

interface TestEventState {
  events: ITestEvent[];
}

const initialState: TestEventState = {
  events: [],
};

const testSlice = createSlice({
  name: 'test',
  initialState,
  reducers: {
    addEvent(state, action: PayloadAction<AddEventPayload>) {
      state.events.push(action.payload.event); // Error here
    },
  },
});

下面是说明问题的打字机游乐场链接。

https://typescriptlang.org/play link here

通过createReducer创建减速器时也会发生同样的情况。

这是对TypeScript的某种限制吗?/这是预期的吗?

1 个答案:

答案 0 :(得分:0)

这似乎是immer类型Draft的问题。

Draft<typeof initialState>的结果似乎与其中的原始Event类型略有不同。

但是,通常不建议这样做,这也可能导致运行时问题,甚至当redux devtools尝试显示该事件时,它们也会崩溃。

仅建议将可序列化的普通对象置于状态: https://redux.js.org/style-guide/style-guide/#do-not-put-non-serializable-values-in-state-or-actions