Reputation: 415
I'm defining a column for my table in react-table. I'm using Typescript so I need to define the type for my columns. For some reason when I define my columns in a custom made hook, the columns become a string when I import the hook and try to pass it to my Table component.
Below my custom hook where I define my columns:
const useBooksColumns = () => {
const [sort, setSort] = useState("name");
const [order, setOrder] = useState("asc");
const columns: ColumnDef<Book>[] = useMemo(
() => [
{
header: "ID",
accessorKey: "id",
},
{
header: "ISBN",
accessorKey: "volumeInfo.industryIdentifiers",
},
{
header: "Title",
accessorKey: "volumeInfo.title",
},
{
header: "Authors",
accessorKey: "volumeInfo.authors",
},
{
header: "Publication date",
accessorKey: "volumeInfo.publishedDate",
},
],
[]
);
return [sort, order, columns];
};
export default useBooksColumns;
And here I try to use it:
const [sort, order, columns] = useBookColumns();
<Table
data={response?.data.items ? response?.data.items : []}
columns={columns}
/>
Now the message I'm getting is as follows: Type 'string | ColumnDef<Book, unknown>[]' is not assignable to type 'ColumnDef<any, any>[]'. Type 'string' is not assignable to type 'ColumnDef<any, any>[]'.
Now changing the type to string | ColumnDef<Book, unknown>[] isn't an option since the useTable hook I'm using from tanstack/react-table doesn't take a string and gives me an error when I change it.
Does anyone know how to handle this?
Upvotes: 0
Views: 1348
Reputation: 866
Typescript is not assuming an array literal as tuple per default so [1, "hi"]
is inferred as (string | number)[]
and not as [number, string]
, to do so, the easiest way is to append it by as const
so your example becomes:
return [sort, order, columns] as const
Upvotes: 0