promise + redux + redux-thunk:typescript error“不能赋值为'Promise <any>'

时间:2017-04-13 23:58:47

标签: typescript promise redux redux-thunk

我试图理解声明promises的类型是如何工作的。

我有一个带有react-thunk的redux webapp用于异步操作。流程是:

  1. React组件调用redux action(workbench-group.view.tsx)和sets是自己的加载状态
  2. redux操作调用api服务(workbench-group.actions.ts
  3. api服务返回承诺
  4. api服务发出HTTP请求(api.service.ts
  5. api服务解决承诺
  6. redux行动获得承诺&amp;调度存储操作
  7. React组件获得承诺&amp;禁用自己的加载状态
  8. 一切正常,但我收到以下打字稿错误:

    ERROR in [at-loader] ./src/actions/workbench-groups.actions.ts:8:3
    TS2322: Type '(dispatch: any) => Promise<any>' is not assignable to type 'Promise<any>'.
    Property '[Symbol.toStringTag]' is missing in type '(dispatch: any) => Promise<any>'.
    

    以下是三个组成部分的相关部分:

    工作台-group.view.tsx

      componentDidMount() {
    this.setState({isFetchingWbGroups: true});
    this.props.wbGroupActions.fetchWbGroups()
      .then(() => {
        this.setState({isFetchingWbGroups: false});
      });
    

    }

    工作台-group.actions.ts

    const fetchWbGroupsAction = createAction(WorkbenchUserActions.WORKBENCH_GROUPS_FETCHED, workbenchGroups => workbenchGroups);
    export const fetchWbGroups = ():Promise<TResponseData> => {
      return (dispatch) => {
        return fetchWithAuth(ApiRoutesService.wbGroups.routes.fetchWbGroups.path, 'GET', null, dispatch)
          .then((response) => {
            return dispatch(fetchWbGroupsAction(response.data));
          }, (err) => {
            console.log('err', err)
          });
      }
    };
    

    api.service.ts

    export const fetchWithAuth = (url: string, method: TMethod = 'GET', data: any = null, dispatch):Promise<TResponseData> => {
      const headers = {
        "Content-Type": "application/json",
        "Authorization": getFromStorage('auth_token')
      };
      return fetchData(url, method, data, dispatch, headers);
    };
    
    
    const fetchData = (url: string, method: TMethod = 'GET', data: any = null, dispatch, headers): Promise<TResponseData> => {
      return new Promise((resolve, reject) => {
        const options = {
          body: data ? JSON.stringify(data) : null,
          method,
          headers
        };
        // here comes a lot of more stuff...
    

    正如我所说,承诺在上述任何一个函数中正确传递并解决/拒绝,只是抱怨的打字稿。我究竟做错了什么?我想我必须在动作中返回的承诺中添加Dispatch类型,但我找不到任何内部的redux-thunk或redux-thunk类型。

1 个答案:

答案 0 :(得分:0)

这是因为您的fetchWbGroups函数实际上正在返回一个函数,其形状为(dispatch: any) => Promise<any>,而不是返回Promise<any>

return (dispatch) => { // this function takes input of a "dispatch" function
    // and return a Promise
    return fetchWithAuth(ApiRoutesService.wbGroups.routes.fetchWbGroups.path, 'GET', null, dispatch)
      .then((response) => {
        return dispatch(fetchWbGroupsAction(response.data));
      }, (err) => {
        console.log('err', err)
      });
 }

考虑改变你的类型声明吗?