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

TypeScript React中如何从第一个参数类型推导第二个参数类型

解决方案

问题根源在于你依赖了typeof OldComponent.propTypes来推导类型,但propTypes是React用于运行时属性校验的对象,它的类型是React.WeakValidationMap<P>,而非组件实际接收的Props类型P。要解决类型推导问题,需要直接提取组件的Props类型,而非依赖propTypes。

正确实现方式(泛型版本)

利用TypeScript泛型结合React内置的ComponentType类型,直接绑定组件的Props类型:

import type { ComponentType } from 'react';

function makeNewComponent<P>(
  OldComponent: ComponentType<P>,
  prepareProps: () => P
): ComponentType {
  return function NewComponent() {
    const oldComponentProps = prepareProps();
    return <OldComponent {...oldComponentProps} />;
  };
}

嵌套函数版本的修正

如果你偏好嵌套函数的写法,同样可以通过泛型实现正确的类型推导:

import type { ComponentType } from 'react';

function makeNewComponent2<P>(OldComponent: ComponentType<P>) {
  return function (prepareProps: () => P) {
    return function NewComponent() {
      const oldComponentProps = prepareProps();
      return <OldComponent {...oldComponentProps} />;
    };
  };
}

使用示例

当你使用上述函数时,TypeScript会自动推导prepareProps的返回类型为目标组件的Props类型:

const OldComponent: React.FC<{ num1: number }> = () => <div>hello</div>;

// 此时TypeScript会强制要求prepareProps返回包含num1的对象
const NewComponent = makeNewComponent(OldComponent, () => ({ num1: 123 }));

// 嵌套版本的使用
const NewComponent2 = makeNewComponent2(OldComponent)(() => ({ num1: 456 }));

关键说明

  • 通过泛型参数P直接关联组件的Props类型,替代了错误的typeof OldComponent.propTypes。
  • 这样不仅能让TypeScript正确推导prepareProps的返回类型,还能在你返回不符合要求的Props时给出即时类型错误提示,保证类型安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:15:34