【发布时间】: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