【问题标题】:Typescript error when dispatching action created by createAsyncThunk from saga调度由 saga 中的 createAsyncThunk 创建的操作时出现打字稿错误
【发布时间】:2021-08-27 03:15:21
【问题描述】:

例子:

/* 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 effect 来调度 thunk action? 我应该怎么做才能从 saga 调度这个动作?

UPD: Action 以这种方式分派,并且工作正常,但仍然存在 TS 错误。

【问题讨论】:

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


    【解决方案1】:

    是的,不幸的是,查看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>;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2020-12-10
      • 2023-03-27
      • 2017-11-28
      相关资源
      最近更新 更多