'Type 'Dispatch<SetStateAction<any[]>>' is not assignable to type '(values?: string) => void'

I'm very new to typescipt and trying to make a basic pin-input page. Sandbox link for my code . Although it is working, I'm getting this error for onChange function at line 10:

Type 'Dispatch<SetStateAction<any[]>>' is not assignable to type '(values?: string) => void'. Types of parameters 'value' and 'values' are incompatible. Type 'string' is not assignable to type 'SetStateAction<any[]>'.ts(2322)

I'm importing react-hook-pin-input and I'm unable to find any demos to use onChange in ts. Please help me re-write onChange such that valueE becomes the value that is being entered. Source for react-hook-pin-input can be found here - https://github.com/elevensky/react-hook-pin-input



Solution 1:[1]

Notice that onChange is of type (values?: string) => void and you passing setValueE which is of type React.Dispatch<React.SetStateAction<string[]>> which means setValueE accepts string[] and you passing a string type on writing onChange={setValueE}.

It works for you only by mistake, because you init valueE with string but then change it to string type, for it to work as expected do something like:

export default function App() {
  const [valueE, setValueE] = useState<string[]>([]);
  return (
    <div className="App">
      <h1>???</h1>
      <PinInput
        fields={4}
        values={valueE}
        onChange={(string) => setValueE([...string])}
      />
      <div> {valueE} </div>
    </div>
  );
}

Edit blissful-resonance-v3lwz

Solution 2:[2]

I faced this issue, almost like your problem, I had

const [code, setCode] = useState('');
<TextField
   label="code"
   value={code}
   onChange={setCode}
/>

Typescript didn't appreciate it, the type of the dispatcher and the eventHandler were not the same.

Type 'Dispatch<SetStateAction>' is not assignable to type 'ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>'

Then I came up with this wrapper function, which fixes the problem.

function withEvent(func: Function): React.ChangeEventHandler<any> {
  return (event: React.ChangeEvent<any>) => {
    const { target } = event;
    func(target.value);
  };
}

// then wrap your function with it
<TextField label="code" value={code} onChange={withEvent(setCode)} />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dennis Vash
Solution 2 gxmad