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

如何在接收组件与Props的类中自动推断Props类型?

如何让WrapperConfig根据传入的Component自动推断props类型?

我正在为一个类添加类型定义,该类接收两个参数:一个Component组件及其对应的props。现有代码如下:

interface WrapperConfigArgs<Props = any> {
    Component: React.ComponentType<Props>
    props: Props
}

class WrapperConfig {
     constructor(args: WrapperConfigArgs) {
         Object.assign(this, args);
     }
}

请问能否根据传入的Component自动推断出props的类型?例如当传入如下HelloWorld组件时,让props自动获得{name: string}的类型提示:

const HelloWorld = ({ name }: { name: string }) => <h1>Hello {name}</h1>

const wrapper = new WrapperConfig({
    component: HelloWorld, 
    props: // 期望自动推断为{name: string}
})

可以实现,只需要把WrapperConfig改成泛型类,让TypeScript能根据传入的Component自动推导props类型。另外注意你代码里的属性名大小写不一致(接口里是Component,实例化时用了component),需要统一,否则会导致类型不匹配。

修改后的完整代码如下:

import React from 'react';

interface WrapperConfigArgs<Props = any> {
    // 统一属性名为小写component,和调用时保持一致
    component: React.ComponentType<Props>;
    props: Props;
}

// 让类接收泛型参数Props
class WrapperConfig<Props> {
    component: React.ComponentType<Props>;
    props: Props;

    constructor(args: WrapperConfigArgs<Props>) {
        Object.assign(this, args);
    }
}

// 测试组件
const HelloWorld = ({ name }: { name: string }) => <h1>Hello {name}</h1>;

const wrapper = new WrapperConfig({
    component: HelloWorld,
    props: { name: "TypeScript" } // 这里会自动提示name为string类型,传其他类型会报错
});

关键变化说明:

  • 将WrapperConfig定义为泛型类WrapperConfig<Props>,显式声明类的属性类型为Props相关类型
  • 构造函数参数指定为WrapperConfigArgs<Props>,让TypeScript通过传入的component自动推导出Props的具体类型
  • 统一了属性名的大小写(接口和实例化时都用component),避免类型不匹配问题

这样当你传入HelloWorld组件时,props就会自动获得{name: string}的类型提示,而且如果传入不符合类型的props,TypeScript会直接报错提示。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:50:26