【问题标题】:functional React components with TypeScript using generic props使用通用道具的 TypeScript 功能性 React 组件
【发布时间】:2021-10-22 01:55:38
【问题描述】:

我正在尝试理解和解决我自己的与反应组件通用道具相关的问题。我从这篇文章functional React components with TypeScript using generic props 中获取了这个代码示例。 不幸的是,我无法在 Codesandbox 中重现相同的内容,并且出现 ts 错误。 沙盒链接 - link to sandbox

Typescript 无法推断 Tablle 对象的正确类型并引发错误

类型“ObjectType”上不存在属性“title”

我不知道我做错了什么,但似乎我只是从文章中复制了一部分代码并且它不起作用。

import { render } from "react-dom";
import React, { PropsWithChildren } from 'react';


interface Props<ObjectType> {
  objects: ObjectType[];
  properties: {
    key: keyof ObjectType,
    title: string,
  }[];
}

function Table<ObjectType,>(
  { objects, properties }: PropsWithChildren<Props<ObjectType>>,
) {
  return (
    <table>
      <tbody>
        {
          objects.map(object => (
            <div>{object.title}</div>
          ))
        }
      </tbody>
    </table>
  );
}

const PostsPage = () => {
  const posts = [{id: 1, title: 'fsdf'}, {id: 2, title: '222fsdf'}];
  return (
    <div>
      <Table
         objects={posts}
         properties={[
           {
              key: 'title',
              title: 'Title'
            },
         ]}
      />
    </div>
  );
};

const rootElement = document.getElementById("root");
render(<PostsPage />, rootElement);

【问题讨论】:

    标签: reactjs typescript typescript-generics


    【解决方案1】:

    通常泛型表示为&lt;T&gt;,可以是任何类型。 T 或 (ObjectType) 不保证它可能具有哪些属性。如果你尝试访问 TypeScript 不知道的属性,它会报错。

    如果你想断言ObjectType 有一个title 属性,你可以这样做

    type WithTitle = {
      title: string;
    };
    
    <ObjectType extends WithTitle>
    

    或者创建一次性对象

    <ObjectType extends { title: string }>
    

    虽然您可以使用&lt;ObjectType&gt; 作为您的模板,但我还是建议您坚持使用&lt;T&gt;,因为它是通用约定,而且您不会认为T 是一个已定义的类型,而您可能正在寻找ObjectType 的定义。

    【讨论】:

      猜你喜欢
      • 2020-08-14
      • 1970-01-01
      • 2020-06-30
      • 2020-12-21
      • 2020-11-27
      • 2017-03-05
      • 2020-04-30
      • 2020-09-09
      • 2020-08-29
      相关资源
      最近更新 更多