DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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 (
      <div>
         <h1>Counter: {counter}</h1>
         <button onClick={() => setCounter(++counter)}>+</button>
         <button onClick={() => setCounter(--counter)}>-</button>
      </div>
   )
}

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

const mapDispatchToProps = {
   setCounter,
}

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.

Top comments (1)

Collapse
 
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

👋 Haven't Posted on DEV Yet?

Head over to our Welcome Thread and tell us a bit about yourself!