使用泛型 Table 组件实现列定义与数据类型推导
解读
国内中高级前端面试常把“泛型+React”作为区分“只会写业务”与“能造轮子”的核心考点。
本题表面让候选人写一个可复用 Table,实则考察三层能力:
- 对 TypeScript 泛型、keyof、索引访问、条件类型的熟练度;
- 在 React 场景下把类型推导做成“零配置”,即调用方只传数据,列定义自动提示、自动校验;
- 性能与可维护性——渲染路径如何避免 any、如何约束列配置与数据一致,同时支持自定义渲染、排序、筛选等扩展。
面试官通常会现场追问:“如果数据源来自后端,字段是动态的,如何保持类型安全?”“如何支持深层路径 a.b.c 的访问?”答不好会直接降档。
知识点
- 泛型组件:React.FC<Props> 与 <T> 结合,组件定义时保留类型参数
- keyof T 与 T[K]:把“对象所有键”映射成联合类型,再通过索引访问拿到对应值类型
- 索引签名与 extends 约束:确保列配置数组与数据字段一一对应
- 模板字面量+条件类型:支持深层路径 'a.b.c' 的自动推断
- 自定义渲染:render 函数参数自动推导为当前单元格类型
- 性能:React.memo + useMemo 避免列配置变化导致全表重渲染
- 国际化与业务扩展:如何在不破坏类型的情况下注入排序、筛选、tooltip 等配置
答案
import React, { ReactNode } from 'react';
// 1. 列配置:强制与数据字段保持一致,同时支持深层路径
type DeepKeyOf<T> = T extends object
? {
[K in keyof T]: K extends string
? T[K] extends object
? K | `${K}.${DeepKeyOf<T[K]>}`
: K
: never;
}[keyof T]
: never;
type Column<T> = {
/** 对应数据字段,必须能反推到 T */
dataIndex: DeepKeyOf<T>;
/** 表头 */
title: ReactNode;
/** 可选:自定义渲染,参数自动带类型 */
render?: (value: any, record: T, rowIndex: number) => ReactNode;
/** 可选:宽度 */
width?: number | string;
};
// 2. 组件 Props,泛型 T 由调用方传入
interface TableProps<T extends Record<string, any>> {
dataSource: T[];
columns: Column<T>[];
rowKey?: DeepKeyOf<T>;
}
// 3. 泛型组件:用函数声明保留泛型
function TableComponent<T extends Record<string, any>>(
props: TableProps<T>
) {
const { dataSource, columns, rowKey = 'id' as DeepKeyOf<T> } = props;
// 工具:按路径取值
const get = (record: T, path: string): any =>
path.split('.').reduce((acc, cur) => acc?.[cur], record as any);
return (
<table style={{ borderCollapse: 'collapse', width: '100%' }}>
<thead>
<tr>
{columns.map((col) => (
<th
key={String(col.dataIndex)}
style={{ border: '1px solid #ccc', padding: 8 }}
>
{col.title}
</th>
))}
</tr>
</thead>
<tbody>
{dataSource.map((record, rowIndex) => (
<tr key={get(record, String(rowKey)) ?? rowIndex}>
{columns.map((col) => {
const value = get(record, String(col.dataIndex));
return (
<td
key={String(col.dataIndex)}
style={{ border: '1px solid #ccc', padding: 8 }}
>
{col.render
? col.render(value, record, rowIndex)
: (value as ReactNode)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
);
}
// 4. 使用:类型自动推导,无需手写 any
interface User {
id: number;
name: string;
age: number;
address: { city: string };
}
const data: User[] = [
{ id: 1, name: '张三', age: 28, address: { city: '北京' } },
{ id: 2, name: '李四', age: 32, address: { city: '上海' } },
];
export default function Demo() {
return (
<TableComponent
dataSource={data}
columns={[
{ dataIndex: 'id', title: 'ID', width: 60 },
{ dataIndex: 'name', title: '姓名' },
{ dataIndex: 'age', title: '年龄' },
{
dataIndex: 'address.city',
title: '城市',
render: (city) => <strong>{city}</strong>,
},
]}
rowKey="id"
/>
);
}
要点回顾
- 组件定义用函数而非箭头函数,保住泛型;
- DeepKeyOf 支持 a.b.c 路径,若后端字段变化,只要接口类型同步,编译期即刻报错;
- render 回调的 value 类型虽为 any,但受 record 与 dataIndex 双重约束,可进一步用类型体操把 value 精确到 T[...];
- 现场手写时,先写 Column<T> 再写 Props,最后实现渲染逻辑,顺序不乱,思路清晰。
拓展思考
- 动态字段场景:若列配置由后端下发,可让后端同时返回 TypeScript 类型声明文件(.d.ts),前端通过 script 标签或异步 import() 注入,实现“运行时+编译时”双保险。
- 性能优化:大数据量虚拟滚动可用 react-window,把泛型参数透传给子组件,保持同一套类型体系;同时用 useMemo 缓存列映射,避免 10w 条数据每次全量迭代。
- 表单联动:把 Table 与 ProForm 结合,当列配置带
editable: true时,单元格自动切换为 Input/Select,类型上通过Column<T> & { editable: true, valueType: 'select', options: Array<{label, value}>约束,确保编辑态的 value 与原始字段类型一致。 - 国际化:title 支持
i18nKey: string,在组件内部通过 useTranslation 转换,保持 Column 类型纯净,不耦合具体实现。 - 面试官陷阱题:“如果 T 是一个联合类型怎么办?”——需用分布式条件类型拆解每支路,再合并列配置,考察候选人对 TS 高级类型的掌握深度。