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

TypeScript如何定义自动推断泛型的多类型组件接口数组

泛型组件数组的自动类型推断问题

我在特定场景下定义泛型时遇到了问题。

我按照如下方式定义了多个React组件:

type ComponentFunction<T> = (props: T) => void;

interface FooProps {
  bar: string;
}

const Foo: ComponentFunction<FooProps> = ({ bar }) => {};

我希望定义一个结构如下的interface:

interface Component<T> {
  element: ComponentFunction<T>;
  props: T;
}

我的目标是创建一个由该类组件对象构成的数组,无需逐个为数组元素指定泛型参数,泛型类型可根据传入的element属性自动推断,示例写法如下:

const components: Component<?>[] = [
  {
    element: Foo,
    props: {
      bar: "bar"
    }
  },
  ...
]

请问该需求是否可以实现?

编辑1:已将示例中的React.FC替换为更通用的ComponentFunction类型示例。

实现方案

方案1:泛型辅助函数+映射类型推断

借助泛型辅助函数和映射类型,自动遍历传入数组的每一项,匹配推断对应泛型参数:

const componentArray = <T extends any[]>(array: { [I in keyof T]: Component<T[I]> }) => array;

const components = componentArray([
  {
    element: Foo,
    props: {
      bar: "string"
    }
  },
  ...
]);

方案2:存在类型封装

通过高阶类型封装实现存在类型效果,让不同泛型参数的Component可以存入同一个数组:

type SomeComponent = <R>(cb: <T>(component: Component<T>) => R) => R;

const someComponent = <T,>(component: Component<T>): SomeComponent => cb => cb(component);

const components: SomeComponent[] = [
  someComponent({ element: Foo, props: { bar: "string" } }),
  ...
];

以上方案由@jcalz提供。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:09:25