CountD
CountD

Reputation: 55

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>
    )
 }
}

Upvotes: 5

Views: 10665

Answers (2)

Alex198710
Alex198710

Reputation: 91

I resolved the same issue in VSCode just by changing the version of typescript used => open command palette > "select typescript version" > "use workspace version"

Upvotes: 7

kingdaro
kingdaro

Reputation: 12008

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> {

Upvotes: 11

Related Questions