Reputation: 265
I'm trying to learn react with typescript am not sure why I am receiving this error.
I have my CardApp:
public state = {
cards: []
};
public render() {
return (
<div>
<Form onSubmit={this.addNewCard}/>
<CardList cards={this.state.cards}/>
</div>
);
}
The CardList is:
const CardList = (props: ICard[]) => {
return (
<div>
{ props.map((card: ICard) => <Card key={card.id} {...card} />) }
</div>
)
}
With this I receive an error Type '{ cards: never[]; }' is not assignable to type 'IntrinsicAttributes & ICard[]'. Type '{ cards: never[]; }' is not assignable to type 'ICard[]'. Property 'length' is missing in type '{ cards: never[]; }'.
However, if I create a ICards interface:
interface ICards {
cards: ICard[]
}
And use that then CardList is:
const CardList = (props: ICards) => {
return (
<div>
{ props.cards.map((card: ICard) => <Card key={card.id} {...card} />) }
</div>
)
}
This works fine, but I was under the impression that <CardList cards={this.state.cards}/>
was passing an array and not an object with an array property and so the ICards
interface was not necessary.
Upvotes: 2
Views: 6353
Reputation: 112787
The props
object is not the cards
array, but the cards
key in the props
object is.
You can write it like this:
const CardList = (props: { cards: ICard[] }) => {
return (
<div>{props.map((card: ICard) => <Card key={card.id} {...card} />)}</div>
);
};
Upvotes: 1