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

TypeScript中为React动态组件构造添加类型校验的方法

实现方案

要让customCreate方法获得完整的TypeScript类型校验能力,只需要通过泛型+React内置类型工具做类型绑定,让传入组件和对应props的类型自动关联,不需要手动声明每个组件的props类型,TS会自动推导校验。

核心实现

直接替换原代码中customCreate的类型注解即可,完整可运行代码如下:

import React from 'react';

interface IDemoObjectProps {
  demoprop1: string;
  demoprop2: number;
}

class DemoComponent extends React.Component<IDemoObjectProps> {
  render() {
    return <></>;
  }
}

// 带完整类型校验的实现
const customCreate = <T extends React.ElementType>(
  type: T,
  props: React.ComponentProps<T>
) => {
  return React.createElement(type, props);
};

// 合法调用:属性类型、数量都匹配,TS校验通过
const component1 = customCreate(DemoComponent, { demoprop1: 'demo', demoprop2: 2022 });
console.log(component1);

类型说明

  • 泛型参数T extends React.ElementType:约束第一个入参必须是合法的React元素类型,覆盖所有可渲染场景:原生DOM标签(如'div'、'input')、类组件、函数组件、forwardRef/memo包装的高阶组件。
  • React.ComponentProps<T>是React内置的类型工具,会自动从传入的组件T中提取出它要求的合法props类型,直接把第二个入参props约束为该类型,TS会自动完成校验:
    • 缺失组件要求的必填属性会抛出类型错误
    • 传入组件未定义的多余属性会抛出类型错误
    • 属性值类型和组件定义不匹配会抛出类型错误

扩展:支持子节点传入

如果需要和原生React.createElement一样支持传入children子节点,可以把参数调整为如下形式,类型校验逻辑依然完全生效:

const customCreate = <T extends React.ElementType>(
  type: T,
  props?: React.ComponentProps<T> | null,
  ...children: React.ReactNode[]
) => {
  return React.createElement(type, props, ...children);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 17:33:40