DEV Community

Raúl Sánchez
Raúl Sánchez

Posted on

How a Fortune 4 Company Types React Props w/Typescript

Let's create a simple React component

import { connect } from 'react-redux';
import { RootState } from 'store';

import { getCounter } from 'views/counter/state/selectors';
import { setCounter } from 'views/counter/state/slice';

type Props = any; // Next step

export const _Counter = ({ counter, setCounter }: Props) => {
   return (
         <h1>Counter: {counter}</h1>
         <button onClick={() => setCounter(++counter)}>+</button>
         <button onClick={() => setCounter(--counter)}>-</button>

const mapStateToProps = (state: RootState) => ({
   counter: getCounter(state),

const mapDispatchToProps = {

export const Counter = 
   connect(mapStateToProps, mapDispatchToProps)(_Counter);
Enter fullscreen mode Exit fullscreen mode

Now, let's type our props

Note: this will only work if your RootState and actions are typed!

type Props = ReturnType<typeof mapStateToProps> &
   typeof mapDispatchToProps;
Enter fullscreen mode Exit fullscreen mode

What does this give us? Let's take a look...

type Props = {
   counter: number;
   setCounter: (count: number) => {
      type: string;
      payload: number;
Enter fullscreen mode Exit fullscreen mode

Why we do it this way

It's easy to read, concise, and eliminates the possibility of typing props incorrectly. If your root state and actions are typed then mapStateToProps & mapDispatchToProps will be the source of truth for your component prop types.

Discussion (1)

phryneas profile image
Lenz Weber

This is pretty much missing out on the ConnectedProps type that was added quite a while ago to the react-redux typings

Also, generally you should use the useSelector and useDispatch hooks instead of connect, as that increases usability with TypeScript enormously - especially when you use pre-typed-hooks