React + TypeScript で State をもつ class コンポーネントを作成するときは、Generics の第二引数に State の型を指定する
タイトルのまま。
「React + TypeScript で State をもつ class コンポーネントを作成するときは、Generics の第二引数に State の型を指定する」
import React, {Component} from "react"; type AppState = { count: number } class App extends Component<{}, AppState> { constructor(props: {}) { super(props); this.state = { count: 0 } } increment = () => { this.setState({ count: this.state.count + 1 }) }; decrement = () => { this.setState({ count: this.state.count - 1 }) }; render() { return ( <> <div>Count: {this.state.count}</div> <button onClick={() => this.increment()}>increment</button> <button onClick={() => this.decrement()}>decrement</button> </> ) } } export default App;