Problem
Hello, I am new to react and typescript. I am trying to pass a custom interface based variable to my component, but IDE keeps saying my variable is not assignable. I ran through several questions, but most of them were about not designating variable type, and I think my code is okay with that. So I'm totally lost here.
Codes
<Post.tsx>
interface IPostData{
id: number,
title: string,
text: string
}
export type {IPostData}
export const PostBox = (postData: IPostData) => {
const {id, title, text} = postData
return (
<div>
<Box>{id}</Box>
<Box>{title}</Box>
<Box>{text}</Box>
</div>
)
}
<Board.tsx>
import {PostBox, IPostData} from 'Post'
export default function Board(){
const testPostData : IPostData = {
id: 1,
title: "Testing Post Interface",
text: "Testing text too"
}
return (
<div>
<PostBox
postData = {testPostData}
/>
</div>
)
}
Error
Type {postData:IPostData} is not assignable to type 'IntrinsicAttributes & IPostData'.
CodePudding user response:
You have to take props in your postBox component as like
interface IPostData{
id: number,
title: string,
text: string
}
export type {IPostData}
export const PostBox:React.FC<IPostData> = ({id, title, text}) => {
return (
<div>
<Box>{id}</Box>
<Box>{title}</Box>
<Box>{text}</Box>
</div>
)
}
CodePudding user response:
The error that you are seeing is happening because you are trying to pass an object with a property named postData to the PostBox component, but the PostBox component expects to receive an object that implements the IPostData interface directly, without any additional properties.
Here is how you could fix the error:
import {PostBox, IPostData} from 'Post';
export default function Board(){
const testPostData: IPostData = {
id: 1,
title: "Testing Post Interface",
text: "Testing text too"
};
return (
<div>
<PostBox
id={testPostData.id}
title={testPostData.title}
text={testPostData.text}
/>
</div>
);
}
In this code, the Board component is creating an object that implements the IPostData interface and storing it in the testPostData variable. Then, when rendering the PostBox component, it is passing the individual properties of the testPostData object as props, rather than passing the testPostData object itself.
This way, the PostBox component receives the id, title, and text props directly, which matches the expected signature of the PostBox function. The PostBox function can then destructure these props and use them to render the contents of the component.
Note that you could also pass the entire testPostData object to the PostBox component, but you would need to change the PostBox function to expect the testPostData object directly, rather than destructuring the id, title, and text props. Here is how that