【发布时间】:2017-09-10 05:38:16
【问题描述】:
我试图了解为 Promise 声明类型的工作原理。
我有一个带有 react-thunk 的 redux webapp 用于异步操作。流程是:
- React 组件调用 redux 操作 (
workbench-group.view.tsx) 并设置为自己的加载状态 - redux 操作调用 api 服务 (
workbench-group.actions.ts) - api 服务返回一个承诺
- api 服务发出 HTTP 请求 (
api.service.ts) - api 服务解决承诺
- redux action 接收到 promise 并发送 action 到 store
- React 组件收到承诺并禁用自己的加载状态
一切正常,但我收到以下打字稿错误:
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>'.
以下是三个组件的相关部分:
workbench-group.view.tsx
componentDidMount() {
this.setState({isFetchingWbGroups: true});
this.props.wbGroupActions.fetchWbGroups()
.then(() => {
this.setState({isFetchingWbGroups: false});
});
}
workbench-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 类型中找不到任何类型。
【问题讨论】:
标签: typescript promise redux redux-thunk