[英]TypeScript Error: Type 'type' is not assignable to type 'IntrinsicAttributes & 'type' & { children?: ReactNode; }'. How to fix it?
I am doing a small home project to improve my skills in TS.我正在做一个小型家庭项目来提高我的 TS 技能。 Getting data from server, everything is good, posts started to be displayed without errors, but then I decided to put the code with the map in a separate component and ts immediately gave me an error:从服务器获取数据,一切都很好,帖子开始显示没有错误,但后来我决定将带有地图的代码放在一个单独的组件中,ts 立即给了我一个错误:
Type '{ posts: IPost[]; }' is not assignable to type 'IntrinsicAttributes & IPost[] & { children?: ReactNode; }'.
Property 'posts' does not exist on type 'IntrinsicAttributes & IPost[] & { children?: ReactNode; }'.
Main.tsx主文件
export const Main: FC = () => {
const [posts, setPosts] = useState<IPost[]>([]);
useEffect(() => {
try {
const fetchPost = async () => {
const res = await axios.get('/posts');
setPosts(res.data);
};
fetchPost();
} catch (error) {
console.log(error);
}
}, []);
return (
<>
<div className='main-container'>
<NewPosts />
<PostSort />
<Posts posts={posts} />
</div>
</>
);
};
Posts.tsx帖子.tsx
export const Posts: FC<IPost[]> = ({posts}) => {
return (
<div className='post-container'>
{posts.map((post) => (
<Post key={post._id} post={post} />
))}
</div>
);
};
The problem is the way you are defining your prop types under Posts.tsx
.问题在于您在Posts.tsx
下定义道具类型的Posts.tsx
。 Any component props is by design an object, but you are defining it as an array.任何组件道具都是设计一个对象,但您将其定义为一个数组。
You are saying that your props are of type IPost[]
and then you are destructuring them to get a property called posts
.你是说你的 props 是IPost[]
类型,然后你正在解构它们以获得一个名为posts
的属性。
The easiest way to fix this, is to create a new type for the props of Posts.tsx
and have a property posts
of type IPost[]
.解决此问题的最简单方法是为Posts.tsx
的 props 创建一个新类型,并具有Posts.tsx
IPost[]
类型的属性posts
。
// create a new interface for prop types
interface PostsProps{
posts: IPost[];
}
// pass it under the FC generic
export const Posts: FC<PostsProps> = ({posts}) => {
return (
<div className='post-container'>
{posts.map((post) => (
<Post key={post._id} post={post} />
))}
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.