有一个关于带有Redux和redux-thunk的React类型的问题。
我有一个异步动作,我根据自己的API响应来调度动作:
export const myAsyncAction = (id: string) => {
return async (dispatch: Dispatch<{}>) => {
// Dispatch REQUEST Action
dispatch(loadRequest())
const response = await get(`api/something/${id}`)
if (!response.ok) {
// Dispatch the FAILURE action
dispatch(loadFailure('error'))
} else {
const json = await response.json()
// Dispatch the SUCCESS action
dispatch(loadSuccess(normalize(json, mySchema)))
}
}
}
(请告诉我该操作是否也不合适)
然后在我的组件中,我声明mapDispatchToprops
的接口:
interface IComponentMapDispatchToProps {
myAsyncAction: (id: string) => Promise<any>
}
interface IComponentProps
extends IComponentMapDispatchToProps {
}
export class Component extends React.Component<IComponentProps, {}> {
render() {
return <div>Whatever</div>
}
}
const mapDispatchToprops: IComponentMapDispatchToProps = {
myAsyncAction
}
export default connect(
{},
mapDispatchToProps
)(Component)
现在打字稿抱怨mapDispatchToProps
这样说:
Type '() => (dispatch: Dispatch<{}>) => Promise<void>' is not assignable to type '() => Promise<any>'.
Type '(dispatch: Dispatch<{}>) => Promise<void>' is not assignable to type 'Promise<any>'.
Property 'then' is missing in type '(dispatch: Dispatch<{}>) => Promise<void>'.
现在,我认为async
函数的类型是Promise<{}>
类型,这是在抱怨它不是...
如果我将此异步操作注入到另一个withRouter
与connect
耦合的组件中,那么我可以像这样键入它,而打字稿突然变得很高兴:
interface IComponentMapDispatchToProps {
myAsyncAction: () => Promise<void>
}
export default withRouter(
connect(
{},
mapDispatchToprops
)(Component)
)
同一个函数如何根据其调用的位置而具有不同的类型?
此异步函数的正确类型是什么?因为这对我来说不再有意义了。