Repository navigation
Replies: 3 comments
|
You can use creator function with type parameter: import { type ColumnDef } from "@tanstack/react-table";
interface MyTableData {
name: string;
resourceId: string | undefined;
}
function createResourceIdColumn<
TData extends { resourceId: string | undefined },
>(): ColumnDef<TData> {
const columnResourceId: ColumnDef<TData> = {
accessorKey: "resourceId",
cell: (info) => <div>{info.row.original.resourceId}</div>,
header: "RESOURCE ID",
};
return columnResourceId;
}
const columns: Array<ColumnDef<MyTableData>> = [
{
accessorKey: "name",
cell: (info) => <div>{info.row.original.name}</div>,
},
// No error here:
createResourceIdColumn(),
]; |
This comment was marked as spam.
This comment was marked as spam.
|
On the “could it actually break?” part: the cell receives the table as well as the row. For example, a cell typed for I checked the types with Table Core 8.21.3 and TypeScript strict mode. Directly assigning the smaller row’s column definition to the full row’s definition is rejected. The generic factory in the earlier answer produces a valid |
Uh oh!
There was an error while loading. Please reload this page.
My app has a bunch of tables that have similar columns, and I'm trying to ensure those columns look / behave identically across all tables. These definitions are bit involved, with custom headers and value displays, and it's very easy for me to make a change to that column definition in one table but forget to update other tables to match. So I want to extract that column definition to be reusable by multiple tables.
I'm stuck on making that definition type-safe. For instance, if I have a column called
resourceIdthat's typed asstring | undefined, then I could have something like:And then insert it into my table definition as such: (
MyTableDataincludes aresourceIdkey):This works just fine, but Typescript complains with an error similar to:
So is there a proper way of typing sharable column definitions, or is this something that's not supported and my code above may break in some situations?
All reactions