Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next Js & Typescript - Property setState does not exist on type Example

Code works fine, but I can't figure out how to remove this error in VSCode. Thanks for help.

import * as React from 'react';

interface State {
  text: string;
}
export default class Example extends React.Component<State> {
 state: State = {
    text: 'SOME TEXT'
}

private handleChange = () => {
    this.setState({text: 'New Text'}); //error: property setState does not exist on type Example
}

public render(){
    return(
        <div>
        <h2 onClick={this.handleChange}>{this.state.text}</h2>
        </div>
    )
 }
}
like image 912
CountD Avatar asked Dec 13 '22 16:12

CountD


1 Answers

First off, make sure you have the react type definitions installed:

npm install @types/react @types/react-dom

Secondly, the generic for state goes second, not first. The first one is for props.

export default class Example extends React.Component<{}, State> {

Look at the React type definitions to verify this (go to definition on Component). <P, S> means props, then state.

class Component<P, S> {
like image 138
kingdaro Avatar answered Dec 17 '22 23:12

kingdaro