Is it somehow possible to get the values in columns as a type in valueFormatter datacolumn?
So if i were to input id, firstname and lastname as columns like shown below i would only get those as a type on valueformatter function?
Goal is go get the columns (id, firstname and lastname) as type on valueformatter
import "./App.css";
interface TableColumn {
name: string;
// TODO: make this type same as type of the keys in one of the objects in rows
valueFormatter?: (datacolumn: {
id: number;
firstname: string;
lastname: string;
}) => void;
}
interface TableProps {
columns: TableColumn[];
rows: any[];
}
const Table = ({ columns, rows }: TableProps) => {
return (
<div>
<div style={{ display: "flex" }}>
{rows.map((row, index) => (
<div key={`row-${index}`} style={{ display: "inline-flex" }}>
{columns.map((col) => (
<div
key={col.name}
style={{ padding: "1rem", border: "1px solid white" }}
>
{col.valueFormatter ? col.valueFormatter(row) : row[col.name]}
</div>
))}
</div>
))}
</div>
</div>
);
};
function App() {
const columns = [
{
name: "id",
valueFormatter: (row) => {
return row.firstname + "some value";
},
},
{ name: "firstname" },
{ name: "lastname" },
];
const rows = [{ id: 1, firstname: "John", lastname: "Doe" }];
return (
<div className="App">
<Table columns={columns} rows={rows} />
</div>
);
}
export default App;
https://codesandbox.io/p/sandbox/sleepy-thunder-23vwdh?file=%2Fsrc%2FApp.tsx%3A1%2C1-48%2C1
2
Answers
You could separate the row object’s type and valueFormatter function’s type to their own type variables and then use those in both TableColumn and the actual implementation of valueFormatter.
Then you can also type the
rows
prop in Table component properly.The keyword you are looking for is generics. Something like this would work for you.
This way, you can separate your Table component and use it with as many Row types as you wish. export TableColumn and TableProps so that you can use them in your components that will use the Table component.