简体   繁体   English

Typescript 围绕使用 generics 使用扩展 {} 的错误

[英]Typescript error around using generics using extends {}

type List<T> = {
  items: T[];
  clickHandler: (a: T) => void;
};

const List = <T extends {}>({
  items,
  clickHandler,
}: List<T>) => {
  return (
    <div>
      {items.map((item, index) => (
        <div key={index} onClick={() => clickHandler(item)}>
          {item} // error is showing here
        </div>
      ))}
    </div>
  );
};

export default List;

typescript Error Type 'T' is not assignable to type 'ReactNode'. typescript 错误类型“T”不可分配给类型“ReactNode”。 Type '{}' is not assignable to type 'ReactNode'.类型“{}”不可分配给类型“ReactNode”。 Type 'T' is not assignable to type 'ReactPortal'.类型“T”不可分配给类型“ReactPortal”。 Type '{}' is missing the following properties from type 'ReactPortal': key, children, type, propsts(2322)类型“{}”缺少类型“ReactPortal”中的以下属性:key、children、type、propsts(2322)

It seems you want to render the items of type T. You have to ensure react that T is "renderable type".您似乎想要呈现 T 类型的项目。您必须确保反应 T 是“可呈现类型”。

One way to do this is:一种方法是:

const List = <T extends ReactNode>

More info here更多信息在这里

Since you're rendering items as children of div you can also define it as由于您将项目呈现为div的子项,因此您也可以将其定义为

const List = <T extends JSX.IntrinsicElements['div']['children']>(

which internally is defined as React.ReactNode would result in the same as @Svetoslav Retkov's answer内部定义为React.ReactNode的结果与@Svetoslav Retkov 的答案相同

TS Playground TS游乐场

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

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