简体   繁体   中英

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

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

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'. Type 'void' is not assignable to type 'ThunkAction'.

of course, as it does not go via redux connect

so my question is it's safe to use InferThunkActionCreatorType from 'react-redux' library?

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

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.

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

Might generally come in handy :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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