Search code examples
typescriptantd

How can I resolve TypeScript warning for Antd Table's onChange handler in the official Antd AJAX example


I am trying to resolve the following warning:

<Table
      columns={columns}
      rowKey={(record) => record.login.uuid}
      dataSource={data}
      pagination={tableParams.pagination}
      loading={loading}
      onChange={handleTableChange}
    />

onChange function gives following warning shown by Visual Studio Code:

Type '(pagination: TablePaginationConfig, filters: Record<string, FilterValue>, sorter: SorterResult<DataType>) => void' is not assignable to type '(pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<DataType> | SorterResult<...>[], extra: TableCurrentDataSource<...>) => void'.
  Types of parameters 'filters' and 'filters' are incompatible.
    Type 'Record<string, FilterValue | null>' is not assignable to type 'Record<string, FilterValue>'.
      'string' index signatures are incompatible.
        Type 'FilterValue | null' is not assignable to type 'FilterValue'.
          Type 'null' is not assignable to type '(boolean | Key)[]'.ts(2322)
InternalTable.d.ts(21, 5): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & TableProps<DataType> & { children?: ReactNode; } & { ref?: Ref<HTMLDivElement> | undefined; }'
(property) TableProps<DataType>.onChange?: ((pagination: TablePaginationConfig, filters: Record<string, FilterValue | null>, sorter: SorterResult<DataType> | SorterResult<...>[], extra: TableCurrentDataSource<...>) => void) | undefined

It's taken from official Antd docs hosted here: https://ant.design/components/table#components-table-demo-ajax

If you want to quickly try out the code in VS Code I have added it to a Vite based React App in this Github Repo: https://github.com/pritambarhate/antdtablewarning

TSC version is: 4.9.5


Solution

  • Table Filter can be any value (number, string, boolean null...) but in handleTableChange filter type, it doesn't include null type. You can add null in filters: Record<string, FilterValue | null> but you also need to add null in TableParams interface filters and you'll have one more typescript error for sorter after fixing filters type. To fix both issues, you can simply use TableProps onChange type.

    import type { TableProps } from "antd/es/table";
    
    const App = () => {
     const handleTableChange: TableProps<DataType>["onChange"] = (pagination, filters, sorter) => {
        ...rest of the code
      };
    }