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

如何为recompose的Table组件传递泛型T?解决TS报错‘Cannot find name T’

Fixing "Cannot find name 'T'" with Recompose and Generic Table Components

Hey there! Let's sort out that TypeScript error you're facing when trying to add a generic type T to your recompose-enhanced Table component.

The Root Problem

Your current code tries to use T directly in compose<Props<T>, CompProps<T>>, but TypeScript has no idea what T is here—const declarations can't have generic parameters in TypeScript. Generics need to be attached to a function or class, not a plain constant.

Solution 1: Wrap in a Generic Function

The simplest fix is to turn your Table export into a generic function that returns the composed component. This lets you declare the T parameter at the function level, making it available to your Props and CompProps types.

Here's how to adjust your code:

import { compose, setDisplayName, injectSheet } from 'recompose';

// Define your generic prop types first
interface Props<T> {
  // Add your props that depend on T, e.g.:
  rows: T[];
}

interface CompProps<T> extends Props<T> {
  // Props added by recompose HOCs, e.g. classes from injectSheet
  classes: Record<string, string>;
}

// Your base Table component (already generic)
const TableComp = <T>(props: CompProps<T>) => {
  // Your component implementation here
  return <table>{/* Render rows using T */}</table>;
};

// Export a generic function that returns the composed component
export const Table = <T>() => 
  compose<Props<T>, CompProps<T>>(
    setDisplayName('Grid'),
    injectSheet(styles)
  )(TableComp);

How to Use It

When you want to use the Table component, specify the generic type when calling the function:

interface User {
  id: number;
  name: string;
}

// Note the () after Table<User>
<Table<User>() rows={userList} />

Solution 2: Generic Component Wrapper

If you prefer a more natural component usage (without the extra ()), you can wrap the composed component in a generic functional component directly:

export const Table = <T>(props: Props<T>) => {
  // Create the enhanced component inside the generic function
  const EnhancedTable = compose(
    setDisplayName('Grid'),
    injectSheet(styles)
  )(TableComp);
  
  // Pass the generic T to the enhanced component
  return <EnhancedTable<T> {...props} />;
};

How to Use It

This feels like a standard generic component:

<Table<User> rows={userList} />

Why This Works

By moving the generic T declaration to a function (either a function that returns the component, or the component itself), TypeScript can properly resolve the type parameter and apply it to your Props<T> and CompProps<T> interfaces. This eliminates the "Cannot find name 'T'" error because T is now explicitly declared in scope.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:22:38