next.js 如何在使用typescript时正确分配下一个js中的 prop 类型?

nszi6y05  于 2023-04-20  发布在  TypeScript
关注(0)|答案(2)|浏览(151)

这是我的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'.

我做错了什么吗?我不知道。请帮助。

fruv7luv

fruv7luv1#

NextPage基于NextComponentTypeNextComponentType有一个类型参数列表,其中包含初始页面数据(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) => { /*...*/ }

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

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

egmofgnx2#

您可以根据需要使用InferGetStaticPropsTypeInferGetServerSidePropsType
使用您的示例:

import type { InferGetStaticPropsType } from "next";
    
    type Article = {
      userId: number;
      id: number;
      title: string;
      body: string;
    };
    
    const Home = ({articles}: InferGetStaticPropsType<typeof getStaticProps>) => {
      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: Article[] = await res.json();
    
      return {
        props: { articles },
      };
    };
 export default Home;

相关问题