打字稿使用actionType作为子组件中的属性来响应redux和redux-thunk

时间:2020-01-07 12:41:03

标签: reactjs typescript redux redux-thunk

我有一个由两个部分组成的示例任务和任务 在父组件任务中,我已连接商店

type Props = ConnectedProps<typeof connector>
const mapDispatchToProps = { updateTask };
const connector = connect(mapStateToProps, mapDispatchToProps);
export default connector(Tasks)

然后在子 Task 中,我想使用updateTask,因为我不想将每个任务都连接到redux

任务看起来像

type Props = {
  updateTask: typeof updateTask
}

但是该代码导致

类型'(taskId:string,updatedTask:Partial)=> void'不能分配给类型'((taskId:string,updatedTask:Partial)=> ThunkAction'。类型“无效”不能分配给类型“ ThunkAction”。

当然,因为它不会通过redux connect

所以我的问题是,可以使用'react-redux'库中的InferThunkActionCreatorType吗?

type Props = {
  updateTask: InferThunkActionCreatorType<typeof updateTaskAndPropagate>
}

定义是

export type InferThunkActionCreatorType<TActionCreator extends (...args: any[]) => any> =
    TActionCreator extends (...args: infer TParams) => (...args: any[]) => infer TReturn
        ? (...args: TParams) => TReturn
        : TActionCreator;

正是我需要相同的函数参数,但返回类型为空

1 个答案:

答案 0 :(得分:1)

是的,这是您的用例的理想类型。 它是Connect类型(connect函数的签名)中使用的东西,因此它准确地模仿了您要查找的内容。

所以你会做

type Props = {
  updateTask: InferThunkActionCreatorType<typeof updateTask>
}

哦,以防万一您不知道:现在有一种ConnectedProps类型,将使您更容易键入connectdocumentation

通常可以派上用场:)