Home > Net >  Argument of type 'string' is not assignable to parameter of type 'ChangeEventHandler&
Argument of type 'string' is not assignable to parameter of type 'ChangeEventHandler&

Time:09-06

I am learning React Typescript, and I have defined a onChange event props. But getting below mentioned errror.

Input.tsx

type InputProps ={
    value: string,
    handleChange: (event:React.ChangeEventHandler<HTMLInputElement>)=> void;
}

export const Input = (props: InputProps) =>{
    const handleInputChange:React.ChangeEventHandler<HTMLInputElement> =(event)=>{
        console.log(event.currentTarget.value);
        props.handleChange(event.currentTarget.value)//Having issue in this line
    }
    return <input type="text" value={props.value} onChange={handleInputChange} />
}

App.tsx

<Input handleChange={value=> console.log(value)} value=""/>

Error: Argument of type 'string' is not assignable to parameter of type 'ChangeEventHandler'. enter image description here

CodePudding user response:

You've defined handleChange as a function that accepts an event object:

type InputProps ={
    value: string,
    handleChange: (event:React.ChangeEventHandler<HTMLInputElement>)=> void;
// −−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

But you're trying to pass it a string:

props.handleChange(event.currentTarget.value)//Having issue in this line
// −−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^

Either define the function so it accepts a string, or pass it the event object. I would do the former, define it so that it accepts a string:

type InputProps = {
    value: string;
    handleChange: (value: string) => void;
// −−−−−−−−−−−−−−−−^^^^^^^^^^^^^
};

Playground link

But if you prefer, pass it the event object:

type InputProps = {
    value: string;
    handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
// −−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
};

// ...

props.handleChange(event);
// −−−−−−−−−−−−−−−−^^^^^

Notice that the event parameter is ChangeEvent<HTMLInputElement>, not ChangeEventHandler<HTMLInputElement>.

Playground link

CodePudding user response:

I guess what you are looking for is props.handleChange(event) as in the type definition, you already said that the argument event is gonna be of type React.ChangeEventHandler<HTMLInputElement> but as you are using event.target.value which is in fact a string, so you are getting an error.

  • Related