从 saga 调度 createAsyncThunk 创建的动作时出现打字稿错误

时间:2021-06-10 06:09:14

标签: typescript redux redux-saga redux-thunk redux-toolkit

示例:

/* actions.ts */
export const getTeacherChats = createAsyncThunk(
  'messenger/chats',
  async (params, thunkAPI) => {
    const response = await messenger.getTeacherChats()
    if (response.ok) {
      return response.data
    }
    return thunkAPI.rejectWithValue(response.error.text)
  }
)
/* saga.ts */
function* teacherChatsWatcher() {
/* Error on the next line: 
    Argument of type 'AsyncThunkAction<TMessengerChatsResponse, void, {}>' is not assignable to parameter of type 'Action<any>'.
      Property 'type' is missing in type 'AsyncThunkAction<TMessengerChatsResponse, void, {}>' but required in type 'Action<any>'. */
    yield put(getTeacherChats())
}

export default function* messengerSaga() {
  yield fork(teacherChatsWatcher)
}

是否可以通过 redux-saga 的 put 效果来调度 thunk 动作? 我应该怎么做才能从 saga 分派这个动作?

UPD:以这种方式调度动作并且它工作正常,但仍然存在TS错误。

1 个答案:

答案 0 :(得分:0)

是的,不幸的是,查看 https://github.com/redux-saga/redux-saga/blob/24e9a68d621fd2a57a29b3b80e4b54ecb22fa593/packages/core/types/effects.d.ts#L367put 的定义,它只是没有考虑任何其他可能的操作类型。

您可能可以通过扩充这些类型来凑合:

declare module "@redux-saga/core/types/effects" {
  // this is the original definition
  export function put<A extends Action>(action: A): PutEffect<A>;
  // let's add an overload
  export function put<A extends ThunkAction>(action: A): PutEffect<A>;
}