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?
The "Type 'void' is not assignable to type" TypeScript error occurs when we forget to return a value from a function, so the function gets an implicit return type of void . To solve the error, make sure you return a value of the correct type from your functions before the assignment.
What is this? The error message "Argument of type 'void' is not assignable to parameter of type" means that we are passing an argument of type void to a function that expects a parameter of a different type. To solve the error, make sure to return a value from your functions. Copied!
To type the onChange event of an element in React, set its type to React. ChangeEvent<HTMLInputElement> . The ChangeEvent type has a target property which refers to the element. The element's value can be accessed on event.
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
}
onChange={(e: React.ChangeEvent<HTMLInputElement>): void => handleChange(e.target.value)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With