简体   繁体   English

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

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

I have an example of two components Tasks and Task in parent component Tasks I have connected store我在父组件Tasks 中有两个组件 Tasks 和 Task 的示例我已经连接了商店

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

then in child Task I want to use updateTask as I don't want to have connected each task to redux然后在子任务中我想使用 updateTask 因为我不想将每个任务连接到 redux

Task looks like任务看起来像

type Props = {
  updateTask: typeof updateTask
}

but that code leads to但该代码导致

Type '(taskId: string, updatedTask: Partial) => void' is not assignable to type '(taskId: string, updatedTask: Partial) => ThunkAction'.类型 '(taskId: string, updatedTask: Partial) => void' 不能分配给类型 '(taskId: string, updatedTask: Partial) => ThunkAction'。 Type 'void' is not assignable to type 'ThunkAction'. “void”类型不能分配给“ThunkAction”类型。

of course, as it does not go via redux connect当然,因为它不通过 redux connect

so my question is it's safe to use InferThunkActionCreatorType from 'react-redux' library?所以我的问题是使用“react-redux”库中的InferThunkActionCreatorType是否安全?

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

definition is定义是

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

it's exactly what I need same function parameters but the return type is void这正是我需要的相同函数参数,但返回类型为 void

Yes, that's the perfect type for your use case.是的,这是您用例的完美类型。 It is what is being used in the Connect type (the signature of the connect function), so it mimics exactly what you are looking for.它是Connect类型(连接函数的签名)中使用的内容,因此它准确地模仿了您正在寻找的内容。

So you'd do所以你会做

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

Oh, just in case you weren't aware: there is a ConnectedProps type now that will make it easier for you to type connect : documentation哦,以防万一你不知道:现在有一个ConnectedProps类型可以让你更轻松地输入connect文档

Might generally come in handy :)通常可能会派上用场:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM