打字稿抛出“不可分配给类型"IntrinsicAttributes &{ 孩子?:ReactNode;}" [英] Typescript throws "is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }"

查看:324
本文介绍了打字稿抛出“不可分配给类型"IntrinsicAttributes &{ 孩子?:ReactNode;}"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know this has been discussed at length, but not other SO solutions seem to work, or I fail at implementing them.

我是打字稿的新手,有以下几点:

I am brand new to typescript, and have the following:

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,但编译器抛出了这个错误:

While I am not sure I even implemented TypeScript correctly, the compiler throws this error:

输入 '{ 部门:[{ id: number;名称:字符串;}];}' 不可分配给类型 'IntrinsicAttributes &{ 孩子?:ReactNode;}'.类型IntrinsicAttributes &"上不存在属性部门"{ 孩子?:ReactNode;}'.

编译器在 组件上的部门属性下划线.

The compiler underlines the departments prop on the <List> component.

为什么会抛出这个错误,我该如何解决?

Why is this error being thrown, and how do I fix it?

推荐答案

Typescript 试图告诉您,您正在尝试将属性 departments 赋予一个对象(在这种情况下,一个 React组件),它的类型没有该属性.

Typescript is trying to tell you that you're trying to give the property departments to an object (in this case, a React component) which doesn't have that property on its type.

类型 'IntrinsicAttributes &{ 孩子?:ReactNode;}' 只是反应组件的默认类型;如果 departments 不包含在该类型的 props 中(并且它不是),那么你不能将该 prop 传递给 List 组件.

The type 'IntrinsicAttributes & { children?: ReactNode; }' is just the default typing for a react component; provided that departments is not included in the props of that type (and it isn't) then you can't pass that prop to the List component.

为了解决这个问题,你只需要在List的props的定义中添加departments

To fix this, you just need to add departmentsto the definition of List's props

这篇关于打字稿抛出“不可分配给类型"IntrinsicAttributes &amp;{ 孩子?:ReactNode;}&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆