You don't need strict typing, even when using Typescript
I stumbled upon some React code at work that looked more or less like that
type DialogContentProps = {
/* other props */
open: boolean;
setOpen: React.Dispatch<React.SetStateAction<boolean>>;
}
const DialogContent = ({ open, setOpen, ...props }: DialogContentProps) => {/* ... */}
Cool, people use strict typings, I'm happy - I thought. But then it turned out i need to change the provider of the state of mentioned dialog. Instead of keeping it in
useStatehook, I wanted to useuseSearchParams. Problem. SetSearchParams type differs a bit from currentsetOpen` type that my colleague used.That cannot be. Do I have to rewrite the logic of this already bloated and dumb dialog? - intrusive thoughts kept flowing - Why?? It was supposed to be a simple improvement for already beautifully working app.
But I got to work and started thinking for the easiest way out of this situation. What is setState in principle. It's a function that:
- takes callback with previous state as an argument, manipulates its copy it and returns it.
- takes new instance of state.
- returns nothing, we don't assign setState to anything.
Sooo...
type DialogContentProps = {
/* other props */
open: boolean;
setOpen: (open: boolean) => void;
}
const DialogContent = ({ open, setOpen, ...props }: DialogContentProps) => {/* ... */}
when we use it, we just pass setOpen (second element of return array of useState hook) and voila. It works.
Moreover, it works with setSearchParams (second element of return array of useSearchParams hook).
Not bad.
Don't overcomplicate types. I would even say -
** Start with the simplest type implementation that meets the requirements of external provider** ( in that case both useState and useSearchParams).
There is no need for something more complicated and you can always extend. Same goes for using React.FC when you want to have types on children prop.
Let the compiler do its thing and infer whatever values you need it to use.
Writing simple code makes you a better programmer.