I have encountered a small problem converting my app to typescript. Here is the (shortened) code:
I have a type with a simple string property:
export type Person = {
birth_date: string
...
This is used in a custom table component using react-table:
import {useTable, useSortBy, Column} from 'react-table'
const PersonTable: FC<{persons: Person, columns: Column<Person>}> = ({ persons, columns }) => {
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable<Person>({ columns, data: persons }, useSortBy)
...
Because birth_date is formatted YYYY-MM-DD, I want to change it to something readable when defining the columns, where formatDate returns a string:
const columnsPersons = useMemo(() => [
{
Header: 'Birth date',
accessor: (row: Person) => formatDate(row.birth_date)
}
], [])
But when I set
<PersonTable columns={columnsPersons} ...
I get the following error (shortened):
Type '{ Header: string; accessor: string; }' is not assignable to type '{ accessor: "birth_date"; }'.
Types of property 'accessor' are incompatible.
Type 'string' is not assignable to type '"birth_date"'.
I know I can use a function for the accessor, because this works. But I don't know if I'm using and / or typing it correctly. Any help is appreciated.
It looks like you returned wider type from formatDate than the accessor expected. You should return from formatDate a 'birth_date' type, not string. Or describe the column like { 'what returned from formatDate': string } instead of { 'birth_date': string }
// 1.
const formatDate = (date) => return date as 'birth_date'
// 2.
const formatDate = (date: string): 'another_birth_date' => { .... }
const PersonTable: FC<{persons: Person, columns: Column<{'another_birth_date': string}>