Kousha
Kousha

Reputation: 36219

Typescript in React: defining a property on `this`

In my non-tyepscript react component I had

componentWillMount() {
    this.delayedSearch = _.debounce((val) => {
        this.onQuerySearch(val);
    }, 1000);
}

for debouncing typing on an input field. Then on an input field I had <input onChange={event => this.delayedSearch(e.value)}>

Now, however, when I switch to Typescipt, my assignment of the _.debounce gives me an error:

Property 'delayedSearch' does not exist on type 'UserSearch'.

How can I fix this?

Upvotes: 0

Views: 59

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164137

That's because your class doesn't declare to have this delayedSearch property, therefor the compiler can't understand what this property is.

In your class you should have something like:

class MyComponent extends React.Component<MyProps, MyState> {
    private delayedSearch: (val: string) => void;

    componentWillMount() {
        // should be fine now
        this.delayedSearch = _.debounce((val) => {
            this.onQuerySearch(val);
        }, 1000);
    }
}

Upvotes: 2

Related Questions