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

TypeScript函数传入React组件时如何约束props的最小结构

正确实现方式

你可以通过类型推断+约束组件Props的方式实现需求,写法如下:

import type { ComponentType, ComponentProps } from "react";

// 写法1:通过infer提取组件Props类型做约束
function connectRRC<T extends ComponentType<any>>(
  component: 
    // 推断组件的Props类型
    T extends ComponentType<infer P> 
      // 约束Props必须包含id: string
      ? P extends { id: string } 
        ? T 
        : never
      : never
) {
  // 你的函数逻辑
}

// 写法2:拆分双泛型约束,更易读
function connectRRC<P extends { id: string }, C extends ComponentType<P>>(component: C) {
  // 你的函数逻辑
}

两种写法都可以保证只有Props包含id: string的组件才能传入函数,同时会保留组件原有的所有Props类型。


泛型组件不生效的原因&解决方法

你遇到的泛型组件(BadComponent3、BadComponent4)无法通过校验的问题,是TypeScript的类型推断限制导致的:
泛型组件本身是泛型类型构造器,在没有显式指定泛型参数的情况下,TS无法自动推导泛型参数的最终类型,也就无法判断其Props是否满足{id: string}的约束。

解决方法也很简单,传入泛型组件时显式指定它的泛型参数即可:

class BadComponent3<P = { somethingElse: boolean }> extends React.Component<{id:string, otherProp:number} & P> {}
// 显式指定泛型参数
connectRRC(BadComponent3<{}>)
connectRRC(BadComponent3<{ customProp: number }>)

class BadComponent4<P = {}> extends React.Component<{id:string, otherProp:number} & P> {}
// 显式指定泛型参数
connectRRC(BadComponent4<{}>)
connectRRC(BadComponent4<{ a: string; b: number }>)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:45:03