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

TypeScript为可切换wrapper的React组件加类型时报错如何解决

问题解决方案

报错原因

该报错本质是TypeScript无法自动推导解构出的剩余props与as属性对应组件的入参类型匹配:原代码中泛型Props由外部传入,TS无法确认交叉类型DirectProps<Props> & Props剔除as字段后的值,完全符合as对应组件的入参要求,因此抛出了泛型实例化不兼容的错误。

修复后的完整代码

import React from 'react';

interface DirectProps<Props = unknown> {
  as?: string | React.ComponentType<Props>;
}

function GenericComponent<Props = React.HTMLAttributes<HTMLDivElement>>({
  as: Component = "div" as React.ElementType<Props>,
  ...props
}: DirectProps<Props> & Props): JSX.Element {
  // 类型断言告知TS:剩余props完全符合Component的入参要求,逻辑上我们保证透传的属性合法
  return <Component {...(props as Props)}>Here goes children</Component>;
}

用法说明

原有使用方式完全兼容,无需修改调用代码:

  • 默认渲染为div元素,支持所有div原生属性校验:
<GenericComponent onClick={() => console.log("Click")} />
  • 指定渲染为a标签时,支持锚点元素属性校验:
<GenericComponent<React.AnchorHTMLAttributes<HTMLAnchorElement>>
  as="a"
  href="https://stackoverflow.com"
  target="_blank"
/>

内容的提问来源于stack exchange,提问作者Aleksandr K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:39:00