使用打字稿时如何在下一个js中正确分配道具类型?

How to correctly assign types of props in next js while using typescript?

这是我的 index.tsx 文件:

    import type { NextPage } from "next";
    
    type AppProps = {
      articles: {
        userId: number;
        id: number;
        title: string;
        body: string;
      };
    };
    
    const Home: NextPage = ({articles}:AppProps) => {
      return (
        <div>
          <h1>Welcome to {articles.title}</h1>
        </div>
      );
    };

    export const getStaticProps = async () => {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
    const articles = await res.json();
    
      return {
        props: { articles },
      };
    };
 export default Home;

代码确实已呈现,但我的 Home 组件中出现错误。 它显示以下错误消息:

Type '({ articles }: AppProps) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ articles }: AppProps) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ articles }: AppProps) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'articles' is missing in type '{}' but required in type 'AppProps'.

我做错了什么吗?我想不通。请帮忙。

NextPagebased on NextComponentType which has a type parameter list,初始页面数据 (props) 具有默认值 ({}):

// With no type arguments passed in, `props` is of type `{}`
const Home: NextPage = () => { /*...*/ }

props 传递给 NextPage 组件时,您还需要将类型作为参数传递。

这将是一个 TypeScript 错误,因为 articles 在类型 {} 上不存在:

// The `AppProps` annotation types the function argument itself, but with
// no type arguments passed to `NextPage`, `props` is still of type `{}`
const Home: NextPage = ({ articles }: AppProps) => { /*...*/ }

因此,要提供有关 propsNextPage 类型信息,请将 AppProps 作为类型参数传入,如下所示:

// you can omit the type annotation from the function argument as `AppProps`
// will be inferred
const Home: NextPage<AppProps> = ({ articles }) => { /*...*/ }