2017-04-13 106 views
-1

我想了解如何聲明類型的承諾工作。諾言+ redux + redux-thunk:typescript錯誤「是不可分配類型'Promise <any>」

對於異步操作,我得到了一個與react-thunk的REDX Web應用程序。流程是:

  1. 陣營組件調用Redux的動作(workbench-group.view.tsx),並設置爲自己的加載狀態
  2. 終極版動作調用API服務(workbench-group.actions.ts
  3. API服務返回的承諾
  4. API服務,使HTTP請求(api.service.ts
  5. api服務解約承諾
  6. redux行爲承諾&調度行爲存儲
  7. 陣營組件接收承諾&禁用

一切工作正常自身的負荷狀態,但我得到以下打字稿錯誤:

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類型的行動中返回的承諾,但我沒有找到任何內部的重複 - thunk或redux-thunk類型。

回答

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) 
     }); 
} 

請考慮只更改您的類型聲明?

相關問題