T
TanStack12mo ago
xenial-black

generic column cell helper function

is it possible to have a type-safe cell helper function like this? so that it does getValue() for me and I can access it more easily
function cell<TData, TValue>(
f: (value: TValue, orig: TData, props: CellContext<TData, TValue>) => any
) {
return function (props: CellContext<TData, TValue>) {
const value = props.getValue();
const orig = props.row.original;
return f(value, orig, props);
};
}
function cell<TData, TValue>(
f: (value: TValue, orig: TData, props: CellContext<TData, TValue>) => any
) {
return function (props: CellContext<TData, TValue>) {
const value = props.getValue();
const orig = props.row.original;
return f(value, orig, props);
};
}
to be used like
const columnHelper = createColumnHelper<{
id: number;
email: string;
role: string;
}>();

const columns = [
columnHelper.accessor("id", {
id: "id",
cell: cell((v) => <span>{v}</span>),
header: () => <span>Name</span>,
}),
columnHelper.accessor("email", {
id: "name",
cell: cell((v) => <span>{v}</span>),
header: () => <span>Name</span>,
}),
];
const columnHelper = createColumnHelper<{
id: number;
email: string;
role: string;
}>();

const columns = [
columnHelper.accessor("id", {
id: "id",
cell: cell((v) => <span>{v}</span>),
header: () => <span>Name</span>,
}),
columnHelper.accessor("email", {
id: "name",
cell: cell((v) => <span>{v}</span>),
header: () => <span>Name</span>,
}),
];
however the value is always typed as unknown if I define the function inline inside the cell call if it's done outside type safety works
const cellFn = (v: string) => <span>{v}</span>;

const columns = [
columnHelper.accessor("id", {
cell: cell(cellFn), // error here
}),
columnHelper.accessor("email", {
cell: cell(cellFn),
}),
];
const cellFn = (v: string) => <span>{v}</span>;

const columns = [
columnHelper.accessor("id", {
cell: cell(cellFn), // error here
}),
columnHelper.accessor("email", {
cell: cell(cellFn),
}),
];
repro: https://codesandbox.io/p/sandbox/dawn-hill-32md5c?workspaceId=8256b876-f76f-4896-af72-5e665345a9a5
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?