TypeScript如何定义表格列类型绑定rowKey与formatRow类型
TypeScript 实现表格列配置的键与格式化函数类型绑定
核心实现方案
你需要的rowKey合法值约束、formatRow入参与rowKey对应属性类型自动匹配的能力,无法通过单泛型的普通接口直接实现,需要借助映射类型生成联合类型完成:
- 遍历泛型T的所有合法键,为每个键单独生成专属的列配置结构,将
rowKey锁定为当前遍历键的字面量类型,formatRow的泛型参数直接取当前键对应的值类型 - 通过索引访问所有键对应的配置类型,组合为联合类型,TypeScript会自动将
rowKey作为判别字段做类型收窄,实现自动类型校验
首先假设你已有的RowFormatter基础定义(可根据实际业务场景调整返回值类型):
// 格式化函数类型:入参为对应单元格的值,返回渲染内容 type RowFormatter<V> = (value: V) => string | number | React.ReactNode;
核心EnrichedTableColumn类型定义:
export type EnrichedTableColumn<T> = { [K in keyof T]: { title: string; rowKey: K; formatRow?: RowFormatter<T[K]>; } }[keyof T];
类型效果验证
以你给出的TImplementation接口为例:
interface TImplementation { hello: string; goodbye: number; }
- 合法配置会被TS正常识别,
formatRow的入参会根据rowKey自动推导对应类型:
const CORRECT_COLS: EnrichedTableColumn<TImplementation>[] = [ { title: "Hello", rowKey: "hello", // value自动推导为string类型,无需手动标注 formatRow: (value) => `Hello, ${value}!` }, { title: "Goodbye", rowKey: "goodbye", // value自动推导为number类型 formatRow: (value) => `Bye ${value} times` } ];
- 类型不匹配的错误配置会被TS直接标记:
const WRONG_COLS: EnrichedTableColumn<TImplementation>[] = [ { title: "Hello", rowKey: "hello", // ❌ 类型报错:number类型参数不能赋值给string类型 formatRow: (value: number) => `Hello, ${value}!` } ];
扩展用法
如果列配置还有和rowKey无关的通用属性(比如列宽、对齐方式),直接写在映射类型的对象结构中即可,所有列配置都会自动继承这些属性:
export type EnrichedTableColumn<T> = { [K in keyof T]: { title: string; rowKey: K; width?: number; align?: 'left' | 'center' | 'right'; fixed?: 'left' | 'right'; formatRow?: RowFormatter<T[K]>; } }[keyof T];
使用时只需要在标注列数组类型时传入表格行数据对应的接口即可,不需要额外传其他泛型参数。
内容的提问来源于stack exchange,提问作者Raph117
相关产品推荐
相关产品推荐

