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>
)
}
}
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>
)
}
}
Share
Improve this question
asked Jun 23, 2018 at 18:01
CountDCountD
551 gold badge1 silver badge7 bronze badges
1
- 1 So even though it's giving you the error, setstate still works? – Blake Steel Commented Jun 23, 2018 at 18:13
2 Answers
Reset to default 11First 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> {
I resolved the same issue in VSCode just by changing the version of typescript used => open command palette > "select typescript version" > "use workspace version"