Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'void' is not assignable to type '((event: ChangeEvent<HTMLInputElement>) => void) React TypeScript

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?

like image 294
lydal Avatar asked Apr 16 '20 07:04

lydal


People also ask

Is not assignable to type () => void?

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.

Is not assignable to parameter of type void TypeScript?

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!

What is react ChangeEvent?

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.


2 Answers

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
}
like image 195
wentjun Avatar answered Oct 19 '22 17:10

wentjun


onChange={(e: React.ChangeEvent<HTMLInputElement>): void => handleChange(e.target.value)}
like image 8
Dailenis González Frómeta Avatar answered Oct 19 '22 16:10

Dailenis González Frómeta