打字稿引发“不能分配给类型'IntrinsicAttributes&{子代?:ReactNode;}”

时间:2020-05-28 13:52:57

标签: typescript next.js

我知道已经对此进行了详尽的讨论,但是其他SO解决方案似乎无效,否则我将无法实现它们。

我是打字稿的新手,并且具备以下条件:

import faker from "faker";
import React from "react";
import Index from "../components/Index";
import List from "../components/List";

interface Props {
  departments: [
    {
      id: number;
      name: string;
    }
  ];
}

const IndexPage: React.FunctionComponent<Props> = ({ departments }) => {
  return (
    <>
      <Index />
      <List departments={departments} />
    </>
  );
};

export async function getStaticProps() {
  let departments: { id: number; name: string }[] = [];

  for (let i = 0; i < 50; i += 1) {
    const name: string = await faker.company.companyName();
    departments = [...departments, { id: i, name }];
  }

  return {
    props: {
      departments,
    },
  };
}

export default IndexPage;

虽然我不确定我是否正确实现了TypeScript,但编译器会抛出此错误:

Type '{ departments: [{ id: number; name: string; }]; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'departments' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

编译器强调<List>组件上的部门属性。

为什么会引发此错误,我该如何解决?

1 个答案:

答案 0 :(得分:0)

Typescript试图告诉您您正在尝试将属性departments赋予对象(在本例中为React组件),该对象的类型上没有该属性。

类型'IntrinsicAttributes & { children?: ReactNode; }'只是react组件的默认类型;如果该类型的道具中不包含departments(并且没有),那么您就不能将该道具传递给List组件。

要解决此问题,只需在departments道具的定义中添加List