I have a reusable component that i pass rows and headings to it as props where ever i use the component. the only problem i have is how to pass types as props to this component?
here is my reusable component
import { TableCell, TableRow } from "@mui/material";
import TableCellOperations from "./table-cell-operations.componenet";
import { PropertyListItem } from "@slice/properties.slice";
interface Props {
rows?: PropertyListItem[];
headings: HeadingsTypes[];
}
export interface HeadingsTypes {
id: string;
title: string;
label: string;
}
const TableRowsComponent: React.FC<Props> = ({ rows, headings }) => {
return (
<>
{rows?.map((row) => (
<TableRow key={row.id}>
{headings.map((heading) => (
<TableCell key={heading.id} align="center">
{typeof row[heading.id] === "object" && row[heading.id] !== null
? row[heading.id]?.title
: heading.id === "status"
? row.status == 0
? "منقضی"
: "فعال"
: row[heading.id]}
</TableCell>
))}
<TableCellOperations />
</TableRow>
))}
</>
);
};
export default TableRowsComponent;
my rows type could be diffrent by situation. in here i put PropertyListItem as rows types but maybe types of rows change. so i want to pass type of rows as a props to this reuseable component. what should i do?
3
Answers
I would suggest making
TableRowsComponent
a generic using TS. This will allow you to use any type for the rows prop.Example:
When you use
TableRowsComponent
, you will specify the type for rows like this:For those cases, you can use generic typing !
The type will then automatically be infer while passing a typed array into the prop
rows
See the doc for more information
One way to pass the type of rows as a prop to your reusable component is to use a generic type parameter in the component definition. Here’s an example:
In this example, we’ve added a generic type parameter
T
to the component definition, which extendsRecord<string, any>
. This means thatT
can be any object type. We’ve then usedT
as the type of therows
prop in theProps
interface, and as the type of therow
parameter in themap
function.When you use the
TableRowsComponent
in your code, you can specify the type of rows by passing it as the generic type argument, like this:Replace
MyRowType
with the type of your rows.