Passing the useReducer dispatch down as a prop in typescript, what type to use?

Viewed 1124
const [state, dispatch] = useReducer(reducer, initialState);

return (
<Component dispatch={dispatch} />
)

// component file
const Component = ({dispatch}: ???) => ..... 

What should I put at the question marks?

1 Answers

Check @types/react. We can see that there are several overloaded definitions of useReducer, but it will return the type Dispatch: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts#L876

You can import Dispatch from 'react'.

Note that Dispatch is generic. The generic type represents possible values for dispatched actions. It's up to you to define these, but reducers commonly use action.type.

import { Dispatch, FunctionComponent } from 'react';

interface ComponentProps {
  dispatch: Dispatch<{ type: string }>
}

const Component: FunctionComponent<ComponentProps> = ({ dispatch }) =>
Related