如何从 redux-toolkit 打字脚本 createAction 不出错

How to typescript createAction from redux-toolkit to not get errors

我需要输入一些道具和参数这是部分代码。 createAction应该怎么写才正确?

const onSubmitHandler = (userFormData: TuserDataFromForm) => {
  console.log("this work");
  // here is error - userFormData
  dispatch(asyncAction(userFormData));
};


function* watchFunc() {
  // here is error - asyncAction.type
  yield takeEvery(asyncAction.type, workFunc);
}


// What should I write instead of any
// to not get error here - dispatch(asyncAction(userFormData)) - in Component
// and here - takeEvery(asyncAction.type, workFunc) - in sagas
const asyncAction: any = createAction("ASYNC_ACTION");

完整代码如下:

https://codesandbox.io/s/saga-redux-toolkit-actions-reducers-of-slices-2f7tx?file=/src/redux/actions.ts

编写 redux 工具包类型时考虑到您不应自己定义它们。

写入

const asyncAction = createAction<TuserDataFromForm>("ASYNC_ACTION");

这里没有必要为变量指定类型。

以后请查看the API documentation——TypeScript几乎完全可用。

至于在 saga 中的用法,请执行以下任一操作

  yield takeEvery(asyncAction, workFunc);
// or
  yield takeEvery(asyncAction.match, workFunc);

您可能还想看看 typed-redux-saga,因为它与 TS 集成得更好:

import { take } from "redux-saga/effects";

function* exampleSaga() {
  // cannot be inferred and needs to be manually typed
  const action: IncrementActionType = yield take(slice.actions.incrementBy);
}

对比:

import { take } from "typed-redux-saga";

function* exampleSaga() {
  // correctly inferred as { payload: number; type: string; }
  const action = yield* take(slice.actions.incrementBy);
}