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

TypeScript自定义可复用表格组件的rows属性类型如何定义?

可复用表格rows属性TS类型定义方案

可复用表格要支持任意结构的行数据,同时保留类型安全性,使用TS泛型实现是最优方案,具体修改如下:

1. 改造类型定义,增加泛型参数

给TablePropsTypes增加泛型参数T,用于动态接收用户传入的行数据类型:

export interface IColumn {
    field: string;
    fieldName: string;
    fieldType: 'number' | 'string';
    editable?: boolean;
}

export interface IColumns extends Array<IColumn> {}

// 新增泛型T,默认值设为Record<string, any>,兼容无显式传类型的场景
export type TablePropsTypes<T extends Record<string, any> = Record<string, any>> = {
    columns: IColumns;
    rows: T[]; // 替换原有的Array<Object>
    actions: boolean;
}

2. 改造组件为泛型组件

组件定义处同步声明泛型,透传给TablePropsTypes:

const CustomTable = <T extends Record<string, any>>({ columns, rows, actions }: TablePropsTypes<T>) => {
  // 组件原有逻辑
}

3. 组件使用示例

用户调用组件时可以传入自定义的行类型,获得完整的类型校验和提示:

// 业务侧自定义行数据类型
interface IProductRow {
  productId: number;
  productName: string;
  price: number;
}

// 调用组件时指定泛型
<CustomTable<IProductRow>
  columns={[
    { field: 'productId', fieldName: '商品ID', fieldType: 'number' },
    { field: 'productName', fieldName: '商品名称', fieldType: 'string' },
    { field: 'price', fieldName: '售价', fieldType: 'number' }
  ]}
  rows={[
    { productId: 1, productName: '测试商品', price: 99 }
  ]}
  actions={true}
/>

如果传入的rows字段和定义的IProductRow不匹配,TS会直接抛出类型错误,避免运行时问题。

进阶类型安全优化(可选)

如果需要约束columns的field字段只能是行类型的属性名,可以进一步把IColumn也改造成泛型:

// IColumn增加泛型约束
export interface IColumn<T extends Record<string, any>> {
    field: keyof T; // field只能取T的属性名,写错会直接报错
    fieldName: string;
    fieldType: 'number' | 'string';
    editable?: boolean;
}

export type TablePropsTypes<T extends Record<string, any> = Record<string, any>> = {
    columns: IColumn<T>[];
    rows: T[];
    actions: boolean;
}

内容的提问来源于stack exchange,提问作者Влад

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:36:02