React Typescript SetStateAction Generic mixup?

Viewed 1449

I personally didn't know how to word this question. The issue I am running into involves me passing down a setState hook into a child component, but it's not always the same setState action if that makes sense.

For example, lets say i have setState(a) which is expecting a parameter of string and that same child component may end up getting a setState(b) which is expecting a parameter of number... now in reality, the parameters that the child is expecting are different types of generics if that makes sense.

So for simplicity, I would create the component which expects one prop that would involve either the setState(a) or the setState(b). Now I get an error saying type React.Dispatch<React.SetStateAction<string | number | undefined>> is not assignable to type React.Dispatch<React.SetStateAction<string | undefined>>

How do I set it so it can expect either a string, number, or undefined. Understanding that in some situations a number is not even an option for it or a string is not even an option for it to accept as a parameter.

SORRY FOR THE CONFUSING QUESTION, I tried my best to explain this. I'm somewhat new to Typescript and am trying to figure out the best way to work with it and React at the same time! (I'm somewhat new to hooks as well too!)

Thank you all in advance!!

Edit: A better example

  const [a, setA] = useState<string | undefined>();
  const [b, setB] = useState<number | undefined>();

  if (something) {
    return (
      <CustomChildComponent useThisState={setA}/>
    )
  } else if (somethingElse) {
    return (
      <CustomChildComponent useThisState={setB}/>
    )
  }

The Error in CustomChildComponent when passing in this prop will say:

(JSX attribute) useThisState: React.Dispatch<React.SetStateAction<string | number | undefined>> Type 'Dispatch<SetStateAction<string | undefined>>' is not assignable to type 'Dispatch<SetStateAction<string | number | undefined>>'.

I hope this clarifies the issue a bit more!

0 Answers
Related