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

Time:01-27

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

CodePudding user response:

The issue is with your interface

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

CodePudding user response:

You define searchChange as an Event I think in your code what you meant to do is define searchChange as a method that accept event: ChangeEvent<...> as an argument. This means you have to change the ISearchBoxProps interface to have the type (event: ChangeEvent<...>) => void for prop searchChange.

  • Related