typescript 在子组件中使用 actionType 作为 属性 来反应 redux 和 redux-thunk

typescript react redux and redux-thunk using actionType as property in child component

我有两个组件任务和任务的例子 在父组件 Tasks 我已连接商店

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
}

但该代码导致

Type '(taskId: string, updatedTask: Partial) => void' is not assignable to type '(taskId: string, updatedTask: Partial) => ThunkAction'.   Type 'void' is not assignable to type '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;

这正是我需要的相同函数参数,但 return 类型为 void

是的,这是您用例的完美类型。 它是 Connect 类型(连接函数的签名)中使用的内容,因此它完全模仿您正在寻找的内容。

所以你会这样做

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

哦,以防万一你不知道:现在有一个 ConnectedProps 类型可以让你更容易地输入 connectdocumentation

一般情况下可能会派上用场:)