table: Type 'string' is not assignable to type '"col1" Typescript error TS2322

Describe the bug (required) Type ‘string’ is not assignable to type '“col1”

Provide an example via Codesandbox! (required) I tried to produce a typescript react-table example without luck. i am really sorry

Steps To Reproduce (required)

`    const data = React.useMemo(
        () => [
            {
                col1: 'Value 1',
            },
        ],
        []
    );
const columns = React.useMemo(
    () => [{
        Header: 'what',
        accessor: 'col1',
    }
    ],
    []
);


const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
} = useTable( {
    columns,
    data,
} )`

Expected behavior (Recommended) No typescript error

Screenshots image

Desktop (please complete the following information):

  • OS: Linux Mint
  • Browser Chrome
  • Version react-table 7.6.2 “@types/react-table”: “^7.0.25”,

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15

Most upvoted comments

This worked for me:

interface IData {
    col1: string;
    col2: string;
}

const data = React.useMemo<IData[]>(
  () => [
    {
      col1: "Hello",
      col2: "World"
    },
    {
      col1: "react-table",
      col2: "rocks"
    },
    {
      col1: "whatever",
      col2: "you want"
    }
  ],
  []
);

const columns = React.useMemo<Column<IData>[]>(
  () => [
    {
      Header: "Column 1",
      accessor: "col1"
    },
    {
      Header: "Column 1",
      accessor: "col2"
    }
  ],
  []
);

const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
} = useTable({ columns, data });

Well done man, thanks for that example. I can confirm that resolved things for me. Perhaps you might be able to add that to one of the examples in this repo as I think it’ll help others too.

For clarification, the differences that assisted me between your example and the original were:

  1. Adding a Data interface: interface Data { title: string; captured: string; priority: string; area: string; isService: string; }

  2. Adding a TableProps interface: interface TableProps<D extends object> { columns: Column<D>[]; data: D[]; }

  3. Changing the first line of the Table component to specify the type of the props and use of generics: function Table<D extends object>({ columns, data }: TableProps<D>) {

  4. Finally, changing the columns object instantiation by passing in the type when using memo: const columns = useMemo<Column<Data>[]>(

Thanks again @datner, saved me a lot of time! 👍

I updated my example to remove the any 😉 Had it in the first place since the actual typing is a bit annoying

@ImranCodeBug there are code examples inlined and linked, please read the entire thread!

My pleasure 😄

Hmm, maybe the difference is they type safety. Out of habit I typed the memoized columns you be of type Column<{col1: string}>[], that seems to be the only difference