【问题标题】:Property does not exist on type even though type is declared when typing NextPage即使在键入 NextPage 时声明了类型,属性也不存在于类型上
【发布时间】:2022-02-06 05:00:20
【问题描述】:

props 从getServerSideProps 函数传递给组件。 我已经定义了道具的类型并分配给传递给组件的道具。但它仍然显示 prop as any。

代码:

type BookProps = {
  _id: string;
  name: string;
  slug: string;
  author: string;
  img: string;
  createdAt: string;
  updatedAt: string;
  __v: number;
};

type BooksProps = BookProps[];

const Home: NextPage = ({ books }: BooksProps) => {
  return (
    <div>
      <Head>
        <title>The Stobook</title>
        <meta
          name="description"
          content="stobook is a free app that allows the user to read any book for free"
        />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div style={{ display: "flex" }}>
        <NavContainer />
        <MainContainer books={books} />
      </div>
    </div>
  );
};

export default Home;

export async function getServerSideProps() {
  await dbConnect();

  const resp = await Book.find({});
  const books = JSON.parse(JSON.stringify(resp));
  return {
    props: {
      books,
    },
  };
}

悬停传递的道具时出错:

Property 'books' does not exist on type 'BooksProps'.

悬停组件名称时出错:

Type '({ books }: BooksProps) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ books }: BooksProps) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ books }: BooksProps) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Type '{ children?: ReactNode; }' is missing the following properties from type 'BookProps[]': length, pop, push, concat, and 29 more.

【问题讨论】:

    标签: typescript next.js


    【解决方案1】:

    您错误地将Home 组件props 对象键入为BookProps 的数组。

    您可能的意思是将books 属性键入为BookProps[]

    type HomeProps = {
        books: BookProps[];
    }
    

    然后将这个类型用于组件的 props。

    const Home: NextPage<HomeProps> = ({ books }) => {
        //...
    }
    

    【讨论】:

    • 谢谢,解决了。但是我可以知道为什么将它声明为 props dint 有效吗?比如,我们可以将类型声明为 props 好吗?
    • 是的,你绝对可以做类似const Home = ({ books }: HomeProps) =&gt; { ... } 的事情。但是由于您使用的是NextPage 类型,所以我也使用了它。实际上最好使用const Home: NextPage&lt;HomeProps&gt;,因为它会同时输入组件的props 返回类型。
    • 太棒了!谢谢你:)
    猜你喜欢
    • 2017-12-31
    • 2018-07-19
    • 2010-12-10
    • 1970-01-01
    • 2021-12-15
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多