Home > Net >  Binding element 'posts' implicitly has an 'any' type
Binding element 'posts' implicitly has an 'any' type

Time:05-28

I have this code I'm writing that involves graphql, react and typescript. Halfway in and I'm getting the error message Binding element 'posts' implicitly has an 'any' type. I have no idea what this means and need help. Below is the code where the error is coming from, thanks

import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import {PostCard, Categories, PostWidget} from '../components'
import {getPosts} from '../services'

export default function Home({posts}) {
  return (
    <div className="container mx-auto px-10 mb-8">
      <Head>
        <title>FTS Blog</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
        <div  className='lg:col-span-8 col-span-1'>
          {posts.map((post) => <PostCard post={post} key={post.title}/>)}
        </div>
      
        <div className="lg:col-span-4 col-span-1">
          <div className="classname lg:sticky relative top-8">
            <PostWidget />
            <Categories />
          </div>
        </div>
      </div>

    </div>
  )
}

export async function getStaticProps() {
  const posts = (await getPosts()) || []

  return {
    props:{posts}
  }
}

CodePudding user response:

I think you can simply use the interface in typescript

this syntax will solve your problem:

import type { NextPage } from 'next';

interface HomeProps{
    posts:any[]
}

const Home: NextPage<HomeProps> = ({ posts }) => (
<div className="container mx-auto px-10 mb-8">
    <Head>
        <title>FTS Blog</title>
        <link rel="icon" href="/favicon.ico" />
    </Head>

    <div className="grid grid-cols-1 lg:grid-cols-12 gap-12">
        <div  className='lg:col-span-8 col-span-1'>
            {posts.map((post) => <PostCard post={post} key={post.title}/>)}
        </div>

        <div className="lg:col-span-4 col-span-1">
            <div className="classname lg:sticky relative top-8">
                <PostWidget />
                <Categories />
            </div>
        </div>
    </div>

</div>
  );

export default Home;

CodePudding user response:

This is an error from Typescript letting you know that your prop posts does not have a type defined, so it is being assumed to be the type, any.

You can make the error go away by explicitly giving posts the type of any, but posts is clearly supposed to be an array based on this line on code you have: posts.map((post) => .... So you probably want to give posts the type of an any array like this:

export default function Home({posts}: {posts: any[]}) {

Nextjs has some additional info about how to use getStaticProps with Typescript

  • Related