Search code examples
javascriptreactjstypescriptecmascript-6types

type useState setter in child component


I am trying to pass a useState setter to a child component, but unsure how to type this.

const Parent = () => {
   const [count, setCount] = useState(0);
   return(
     Child count={count} setCount={setCount} />
   );
}

Then in the Child component I am trying to type the setter but I am seeing the following error.

Type 'Dispatch< SetStateAction< string[] > >'is not assignable to type '() => void'.

My code looks like this

type Props = {
  count: number;
  // the issue is the line below
  setCount: () => void;
}

const Child = ({ count, setCount }: Props) => {
    .... code here
}

Solution

  • You can specify that the setCount prop function expects a number as first argument and the error will go away.

    type Props = {
      count: number;
      setCount: (num: number) => void;
    }