SuperAPI AI 工具集

typescript

编程与开发

查看项目

更新于 10-16 02:18

技能介绍

本技能建立在 core 与 table-features 之上,目标是让功能对象与辅助函数把类型传递到用户代码(userland)中。

配置方式

从 @tanstack/table-core 导入 createColumnHelper、metaHelper、tableFeatures:

import {
  createColumnHelper,
  metaHelper,
  tableFeatures,
} from '@tanstack/table-core'

type Person = { id: string; age: number }
type ColumnMeta = { align?: 'start' | 'end' }
const features = tableFeatures({ columnMeta: metaHelper<ColumnMeta>() })
const helper = createColumnHelper<typeof features, Person>()
export const columns = helper.columns([
  helper.accessor('age', { meta: { align: 'end' } }),
])

核心模式

保留异构 accessor 值

const columns = helper.columns([
  helper.accessor('id', { header: 'ID' }),
  helper.accessor('age', { header: 'Age' }),
])

columns() 会保留每个 accessor 的 TValue,而不是把数组类型放宽。

通过 helper 组合选项

const defaults = tableOptions<typeof features, Person>({
  defaultColumn: { meta: { align: 'start' } },
})

对可复用的片段使用 tableOptions;一次性配置直接使用适配器选项即可。

常见错误

[HIGH] 抹掉 accessor 值推断

错误写法:

const columns: ColumnDef<typeof features, Person, unknown>[] = [
  helper.accessor('age', {}),
]

正确写法:

const columns = helper.columns([helper.accessor('age', {})])

宽泛的类型标注会丢弃 accessor 特有的 number 值类型。 来源:docs/guide/helpers.md#createcolumnhelper

[MEDIUM] 手动串联内部 feature 泛型

错误写法:

type Features = TableFeatures

正确写法:

type Features = typeof features

具体注册表才是按 feature 保护的 API 与注册表键的来源。 来源:packages/table-core/src/types/TableFeatures.ts

[MEDIUM] 全局合并每张表的 meta

错误写法:

declare module '@tanstack/table-core' {
  interface ColumnMeta<TData, TValue> {
    align?: string
  }
}

正确写法:

const features = tableFeatures({
  columnMeta: metaHelper<{ align?: 'start' | 'end' }>(),
})

V9 的仅类型 feature 槽位让 meta 类型限定在表格工厂作用域内。 来源:docs/guide/table-and-column-meta.md

API 探索

检查 node_modules/@tanstack/table-core/dist/helpers/ 以及 dist/index.d.ts 中重新导出的签名;避免把深层内部泛型签名复制到应用代码中。