ThunkAction通过分派返回,而不是ThunkAction的返回类型

时间:2020-07-22 01:18:13

标签: reactjs typescript react-redux

如何配置Typescript以使其与react-redux和redux-thunk配合使用,以便dispatch返回要调度的ThunkAction的返回类型,而不是ThunkAction<a,b,c,d,e>

export function addPerson(
  person: Person
): PersonActionTypes {
  return {
    type: ADD_PERSON,
    person,
  }
}


export const savePerson = (
  person: Person
): ThunkAction<
  Promise<Person>,
  RootState,
  unknown,
  Action<string>
> => async (dispatch): Promise<Person> => {
  const savedPerson = await PersonApi.save(person)
  dispatch(addPerson(savedPerson))
  return savedPerson
}

当我分派此操作时,我希望它返回Promise<Person>但分派返回ThunkAction<Promise<void>, RootState, unknown, Action<string>>

const savedPerson = await dispatch(savePerson(person))
// savedPerson is a ThunkAction as far as TypeScript is concerned but I would like it to be a Person.

1 个答案:

答案 0 :(得分:0)

遇到同样的问题。一段时间后,找到了对我有用的解决方案。 这里的问题是,// Use with @input="fetchTutors" on textbox (or any other event) // Must be invoked through the search input element async fetchTutors(event) { await store.dispatch('loadAllTutors', event.target.value); } // Use with v-model="postcode" on textbox // Can be invoked from any element async fetchTutors() { await store.dispatch('loadAllTutors', this.postcode); } 默认情况下的类型为df <- data.frame(a = c(1, 2, 3, 4, 5, NA, NA), b=c(6, 7, 8, NA, 9, 10, NA)) df$new.column <- ifelse(is.na(df$a) & is.na(df$b), 1, 0) df ,对于简单的操作是可以的,但对于dispatch则不是。

我的重击动作描述如下:

Dispatch

我已经为thunk-dispatch创建了类型

ThunkAction

然后,我可以使用返回值而不会出现类型错误,如下所示:

type AppThunk<ReturnType = void> = ThunkAction<ReturnType, StateType, unknown, Action<string>>;
export const thunkAction = (id: number): AppThunk<Promise<{ status: string }>> => async (dispatch) => { ...do something, return correct type };

如果在该特定组件中只有大量的动作要调度,请认为您可以一次定义调度类型

export type AppThunkDispatch = ThunkDispatch<StateType, unknown, Action<string>>;

并避免const data = await (dispatch as AppThunkDispatch)(thunkAction(33)); if (data.status === 'success') { console.log('perfect') } 投射