繁体   English   中英

Typescript 抛出“不可分配给类型 'IntrinsicAttributes & { children?: ReactNode; }”

[英]Typescript throws “is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }”

我知道这已被详细讨论过,但其他 SO 解决方案似乎不起作用,或者我无法实施它们。

我是 typescript 的新手,并且有以下内容:

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>组件上强调了部门属性。

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

Typescript 试图告诉您,您正试图将财产departments提供给 object(在这种情况下,是一个 React 组件),它的类型没有该属性。

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

要解决此问题,您只需将departments添加到List的 props 的定义中

暂无
暂无

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

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