绑定元素 'posts' 隐式具有 'any' 类型

Binding element 'posts' implicitly has an 'any' type

我正在编写的这段代码涉及 graphql、react 和 typescript。中途,我收到错误消息 Binding element 'posts' implicitly has an 'any' type. 我不知道这意味着什么,需要帮助。 下面是错误来源的代码,谢谢

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}
  }
}

这是 Typescript 的一个错误,让您知道您的道具 posts 没有定义类型,因此它被假定为类型 any.

您可以通过 显式 posts 类型 any 来消除错误,但是 posts 显然应该是基于您拥有的这一行代码的数组:posts.map((post) => ...。所以你可能想像这样给 posts 一个 any array 的类型:

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

Nextjs 有一些关于 how to use getStaticProps with Typescript

的附加信息

我想你可以简单地使用打字稿中的界面

此语法将解决您的问题:

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;