javascript에서 typescript로 마이그레이션 중 다음 에러가 발생했다.

문제의 코드는 아래와 같다.
import React from "react";
export class GameStateBar extends React.Component {
constructor(props: any) {
super(props);
this.state = { gameState: "" };
}
handleGameStateChange(e: any) {
this.setState({ gameState: e.detail });
}
handleRestart(e: any) {
this.setState({ gameState: "" });
}
componentDidMount() {
window.addEventListener("gameStateChange", (e) =>
this.handleGameStateChange(e)
);
window.addEventListener("restart", (e) => this.handleRestart(e));
}
componentWillUnmount() {
window.removeEventListener("gameStateChange", (e) =>
this.handleGameStateChange(e)
);
window.removeEventListener("restart", (e) => this.handleRestart(e));
}
render() {
return <div className="gameStateBar"> {this.state.gameState} </div>;
}
}
코드에서 GameStateBar는 React.Component를 extends 하고 있다.
component는 다음과 같이 정의되어있다.
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
P는 props를 S는 state를 의미하고, 각각의 default value가 {}으로 설정되어있음을 알 수 있다.
문제가 발생한 이유는 gameState를 state로 사용하고 있으나 GameStateBar는 {}가 기본 값으로 정의되었기 때문이다.
따라서 다음과 같이 수정하면 오류는 해결된다.
class App extends React.Component<{}, { gameState: string }> {
...
}
혹은,
type MyProps = { ... };
type MyState = { gameState: string };
class App extends React.Component<MyProps, MyState> {
...
}
해결!

참고
https://stackoverflow.com/questions/47561848/property-value-does-not-exist-on-type-readonly
728x90
댓글