Home > Blockchain >  TypeScript Error: Type 'type' is not assignable to type 'IntrinsicAttributes & '
TypeScript Error: Type 'type' is not assignable to type 'IntrinsicAttributes & '

Time:11-09

I am doing a small home project to improve my skills in 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:

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

export const Posts: FC<IPost[]> = ({posts}) => {
  return (
    <div className='post-container'>
      {posts.map((post) => (
        <Post key={post._id} post={post} />
      ))}
    </div>
  );
};

CodePudding user response:

The problem is the way you are defining your prop types under 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.

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[].


// 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>
  );
};

  • Related