Search code examples
javascriptreactjstypescripttanstack-table

Typehinting issue with property accessorKey on @tanstack/react-table


I'm trying to use the @tanstack/react-table package correctly with Typescript, but I keep running into a problem that I haven't been able to solve on my own.

The problem has to do with the accessorKey property. I keep trying to somehow find a typesafe way to access this property, but have not yet been successful.

I first look for a particular column that has the custom property primary in it.

const primaryColumn = columns.find((column) => column.meta?.primary === true)

And then I try to access the accessorKey property on primaryColumn, but every time I do I get a typescript error.

TS2339: Property accessorKey does not exist for type ColumnDef<TData, TValue>.
Property accessorKey does not exist on type
ColumnDefBase<TData, TValue> & StringHeaderIdentifier

Here is my column definition in case it is relevant:

const columns: ColumnDef<Organisation>[] = [
    {
        meta: {
            primary: true
        },
        accessorKey: "name",
        header: ({ column }) => (
            <DataTableColumnHeader column={column} title={"Name"} />
        ),
    },
    ...
]

Has anyone encountered the same problem and knows what to do from here?

If there is any information missing or otherwise, please let me know. I will update the post with the additional information as soon as possible.


Solution

  • My solution

    I finally figured out what I was doing wrong.
    I was iterating directly over the columns array that I was passing from my page component to my table component, which was wrong. tanstack/react-table wants you to iterate over the columns using the provided table.getAllColumns() method. The table variable is an instance of the useReactTable() hook in my code. With this method I was able to get the associated ID, which is the same as the accessorKey.

        const primaryColumn = table.getAllColumns().find((column) => column.columnDef.meta?.primary === true)
        const accessorKey = primaryColumn!.id
    

    TypeScript still thinks that primaryColumn might be undefined (because of the Array.prototype.find() method). So I used the ! to tell TS that I definitely know that this variable exists.