我试图理解声明promises的类型是如何工作的。
我有一个带有react-thunk
的redux webapp用于异步操作。流程是:
workbench-group.view.tsx
)和sets是自己的加载状态workbench-group.actions.ts
)api.service.ts
)一切正常,但我收到以下打字稿错误:
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类型。
答案 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)
});
}
考虑改变你的类型声明吗?