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

React中泛型函数为何无法正确识别自定义类型?

问题原因

你在render函数里写的<Customer>是重新声明的泛型参数,它和你外部定义的Customer类型同名但完全无关。这个泛型参数没有任何类型约束,TypeScript根本不知道它包含customerAddress属性,所以会抛出错误。

解决方案

要让render函数的record类型和业务类型绑定,应该把整个Column类型定义为泛型,而非让render函数单独使用泛型:

步骤1:调整Column为泛型类型

import type { ReactNode } from 'react';

type Column<RecordType> = {
  title?: string;
  key: string;
  className?: string;
  sort?: boolean;
  isVisible?: boolean;
  render?: (record: RecordType) => ReactNode;
  // 补充你用到的filter属性类型
  filter?: { type: string };
};

步骤2:指定columns的泛型参数

定义columns数组时,明确指定泛型为Customer,这样render函数的record会自动推导为Customer类型:

type Customer = {
  customerAddress: { street1: string };
};

const columns: Column<Customer>[] = [
  {
    title: "Street Address",
    key: "customerAddress.street1",
    sort: true,
    filter: {
      type: "string",
    },
    render: (record) => {
      return record?.customerAddress?.street1;
    },
  },
];

多类型场景支持

如果需要同一个columns数组兼容多种业务类型(比如同时处理Customer和Order),可以使用联合类型:

type Order = {
  orderNumber: string;
};

const mixedColumns: (Column<Customer> | Column<Order>)[] = [
  {
    title: "Street Address",
    key: "customerAddress.street1",
    render: (record: Customer) => record?.customerAddress?.street1,
  },
  {
    title: "Order Number",
    key: "orderNumber",
    render: (record: Order) => record?.orderNumber,
  },
];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:30:29