11

Im a beginner in React Typescript, and I have defined some props is a .JS file that I want to use in a .tsx file. but I receive this error on one of my TypeScript lines:

 <MyTextField style={{width:'60%'}}  name='ActivationDate' type='date' defaultValue={values1.ActivationDate} onChange={handleChange('ActivationDate')}/>
Type 'void' is not assignable to type '((event: ChangeEvent<HTMLInputElement>) => void) | ((event: ChangeEvent<HTMLSelectElement>) => void) | ((event: ChangeEvent<HTMLTextAreaElement>) => void) | undefined'.

The CodeSandbox contains both my JS file and TSX file : https://codesandbox.io/s/tsx-rj694

what seems to be the problem and how can I write this correctly?

lydal
  • 802
  • 3
  • 15
  • 33

3 Answers3

44

I assume you are not passing the event object into the handleChange method.

This is how you should amend your onChange event handler:

onChange={() => handleChange('ActivationDate')}

For your information, if you need to access the event object in the onChange call, you will need to explicitly specify the right types.

onChange={handleChange}

And when you define the function,

const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
  // do the rest here
}
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • 1
    in my case I also had to declare explicit type to `handleChange` variable : `const handleChange : ChangeEventHandler = (event: ChangeEvent) => {}` – Michał Krzywański Apr 22 '22 at 17:25
10
onChange={(e: React.ChangeEvent<HTMLInputElement>): void => handleChange(e.target.value)}
0
onChange={handleChange}

in my case I also had to declare explicit type to handleChange variable :

 const handleChange = (event: SelectChangeEvent) => {
    // do the rest here
  } 
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 01 '23 at 06:20