I have a React Class Component with two properties in state. I'm currently getting a TypeScript error when trying to dynamically setState that says Property 'input' does not exist on type 'Readonly<{}>'.
I'm newer to TypeScript and I haven't yet had to tackle the problem of adding Type definitions to a Class Component before. I've been working mostly with functional components and hooks so this issue hasn't come up for me.
I defined the type for my App State and then passed it into the component, but I'm still getting the original error as well as a new error where I define state that says 'AppState' only refers to a type, but is being used as a value here.
I've been searching around for a solution but haven't been able to solve this.
My original component
type AppState = {
input: string;
imageUrl: string;
}
class App extends Component<AppState> {
constructor(props: any) {
super(props);
// Error: 'AppState' only refers to a type, but is being used as a value here.
this.state: AppState = {
input: "",
imageUrl: "",
};
}
onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
this.setState({ input: e.target.value });
};
onButtonSubmit = () => {
// Error: Property 'input' does not exist on type 'Readonly<{}>'.
this.setState({ imageUrl: this.state.input });
clarifaiApp.models
.predict(
Clarifai.COLOR_MODEL,
// URL
"https://samples.clarifai.com/metro-north.jpg"
)
.then(
function (response: any) {
console.log("This is your response: ", response);
},
function (err: Error) {
console.log("There was an error: ", err);
}
);
};
render() {
return (
<Container>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}
/>
{/* Error: Property 'imageUrl' does not exist on type 'Readonly<{}>'. */}
<FaceRecognition imageUrl={this.state.imageUrl} />
</Container>
);
}
}
export default App;