Reputation: 193472
After switching from JavaScript to TypeScript, I get the error:
Property does not exist on type 'ReadOnly <{}>'
in this code:
this.state.flashcards
It seems that I need to define flashcards
as a type, but when I change flashcards: []
to flashcards: any[]
it give me an error that any is being used as a value.
How can I get this could to compile in TypeScript as it does in JavaScript?
import React from 'react';
import Flashcard from './Flashcard';
const flashcards = require('../data/custom/itemType_flashcards.json');
class Main extends React.Component {
constructor(props: any) {
super(props);
this.state = {
flashcards: []
};
}
componentDidMount() {
this.setState({
flashcards
});
}
render() {
return (
<div className="content">
{this.state.flashcards.map(flashcard => <Flashcard {...flashcard} key={flashcard.id} />)}
</div>
);
}
}
export default Main;
Upvotes: 0
Views: 416
Reputation: 85251
When using typescript, React.Component
is a generic which you can use to specify the types of your props and state. If you don't, the default is for props and state to be empty objects, which is then causing an error when you try to assign a state that isn't an empty object. So do something like the following:
interface MainState {
flashcards: FlashcardProps[]; // You'll need to define the shape of FlashcardProps too
}
class Main extends React.Component<{}, MainState> {
// The rest is unchanged
}
Upvotes: 1