You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在useReactTable中使用sortingFns触发TypeScript错误

React Table自定义排序函数的TypeScript错误处理

问题场景

给React Table的某一列添加自定义排序函数时触发TypeScript错误。已按照文档添加模块声明,但在useReactTable配置中传入sortingFns时,TS提示该属性不存在于TableOptions类型中。

已添加的模块声明

declare module "@tanstack/table-core" {
  interface SortingFns {
    myCustomSorting: SortingFn<unknown>;
  }
}

useReactTable配置代码

const table1 = useReactTable({
    data: usersFilter,
    columns,
    initialState: {
      pagination: {
        pageSize: 50
      }
    },
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    sortingFns: {
      myCustomSorting: (rowA: any, rowB: any, columnId: any): number => {
        console.log("hi");
        return 0;
      },
    },
  });

触发的TypeScript错误

Argument of type '{ data: any[]; columns: ColumnDef<AmbassadorType>[]; initialState: { pagination: { pageSize: number; }; }; getCoreRowModel: (table: Table<any>) => () => RowModel<any>; getSortedRowModel: (table: Table<...>) => () => RowModel<...>; getPaginationRowModel: (table: Table<...>) => () => RowModel<...>; sortingFns: { ...; ...' is not assignable to parameter of type 'TableOptions<any>'.
  Object literal may only specify known properties, and 'sortingFns' does not exist in type 'TableOptions<any>'.ts(2345)

解决方案

1. 修正模块声明的目标包

useReactTable属于@tanstack/react-table包,而非@tanstack/table-core,需调整模块声明的目标:

declare module '@tanstack/react-table' {
  // 用你的行数据类型(比如AmbassadorType)代替unknown,获得更严格的类型检查
  interface SortingFns {
    myCustomSorting: SortingFn<AmbassadorType>;
  }
}

2. 为useReactTable指定泛型类型

显式传入行数据的泛型类型,提升类型准确性:

const table1 = useReactTable<AmbassadorType>({
  data: usersFilter,
  columns,
  initialState: {
    pagination: {
      pageSize: 50
    }
  },
  getCoreRowModel: getCoreRowModel(),
  getSortedRowModel: getSortedRowModel(),
  getPaginationRowModel: getPaginationRowModel(),
  sortingFns: {
    myCustomSorting: (rowA, rowB, columnId) => {
      console.log("hi");
      // 这里编写针对AmbassadorType字段的排序逻辑
      return rowA.xxx.localeCompare(rowB.xxx); // 示例排序逻辑
    },
  },
});

3. 确保声明文件被TypeScript识别

检查tsconfig.json的include配置,确保你的.d.ts声明文件所在目录被包含:

{
  "include": [
    "src/**/*",
    "src/types/**/*.d.ts" // 假设声明文件放在src/types下
  ]
}

错误原因

原模块声明针对@tanstack/table-core,但useReactTable的类型定义来自@tanstack/react-table,导致TS无法识别扩展的sortingFns属性。同时,使用unknown作为泛型会丢失类型检查能力,显式指定行数据类型能避免不必要的any类型。

内容的提问来源于stack exchange,提问作者isMattCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 01:27:44