Search code examples
reactjstypescripttypescomponents

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


I am first-time using Typescript to build a project from the ZTM course, which is originally on Javascript. I have encountered an issue, where I can't set a type to the event parameter. It says:

Type '(event: ChangeEvent<HTMLInputElement>) => void' is not assignable to type 'ChangeEvent<HTMLInputElement>'.ts(2322)

Here is my onSearchChange function, located in my App.tsx, which contains the event parameter. With this function, I expect to see console logging of an object, when typing something in the search bar.

onSearchChange(event: ChangeEvent<HTMLInputElement>) {
        console.log(event);
    }

My render method, which renders that function, is below:

render() {
        return (
            <div className='tc'>
                <h1>RoboFriends</h1>
                <SearchBox title='search box' searchChange={this.onSearchChange}/>
                <CardList title='list of robot cards' robots={this.state.robots} />
            </div>
        );
    }

searchChange property is marked with an error, mentioned above:

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

There is my search bar component in my SearchBox.tsx file. It looks as follows:

import { FC, ChangeEvent } from 'react';

interface ISearchBoxProps {
    title: string;
    searchChange: ChangeEvent<HTMLInputElement>;
}

const SearchBox: FC<ISearchBoxProps> = ({searchChange}) => {
    return (
        <div className='pa2'>
            <input
                className='pa3 ba b--green bg-lightest-blue'
                type='search'
                placeholder='search robots'
                onChange={searchChange}
            />
        </div>
    )
    
}

export default SearchBox;

The onChange property is marked by VSCode with errors:

Type 'ChangeEvent<HTMLInputElement>' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.
Type 'ChangeEvent<HTMLInputElement>' provides no match for the signature '(event: ChangeEvent<HTMLInputElement>): void'.

I tried different options, including this gentleman's advice, but I couldn't get rid of these errors: Type 'void' is not assignable to type '((event: ChangeEvent<HTMLInputElement>) => void) React TypeScript


Solution

  • The issue is with your interface

    interface ISearchBoxProps{
     title: string;
     searchChange: (event: ChangeEvent<HTMLInputElement>)=>void
    }