繁体   English   中英

即使声明了类型,属性也不存在于类型上

[英]Property does not exist on type even though type is declared

props 从 getServerSideProps function 传递给组件。 我已经定义了道具的类型并分配给传递给组件的道具。 但它仍然显示 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.

您错误地将Home组件props object 键入为BookProps数组。

您可能的意思是将books道具键入为BookProps[]

type HomeProps = {
    books: BookProps[];
}

然后将此类型用于组件的道具。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM