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

React泛型组件BaseBlock调用时TypeScript报错(2558)求助

解决React泛型ForwardRef组件TypeScript类型报错问题

问题原因

React的forwardRef函数返回的组件类型默认不会保留泛型参数声明,导致你显式传入<string>类型参数时,TypeScript无法识别该组件接受泛型参数,从而抛出Expected 0 type arguments, but got 1错误。

解决方案

需要手动为forwardRef返回的组件指定泛型类型,让TypeScript识别它是一个接受泛型参数的组件。以下是两种常用实现方式:

方式一:利用已有Props类型做断言

直接将forwardRef的结果断言为泛型组件类型,复用你已定义的BaseBlockProps:

import React from 'react';

interface Props<T> {
  id?: string;
  items?: T[];
  children?: (item: T, index: number) => React.ReactNode;
  parentId?: string;
  contentId?: string[];
}

const BaseBlock = React.forwardRef(function BaseBlock<T>(
  { items, children }: React.PropsWithChildren<Props<T>>,
  ref: React.ForwardedRef<HTMLDivElement>
): React.ReactElement | null {
  return (
    <div data-testid="base-block" ref={ref}>
      {items && children && items.map(children)}
    </div>
  );
}) as <T>(props: BaseBlockProps<T>) => React.ReactElement | null;

export type BaseBlockProps<T> = React.PropsWithRef<Props<T>>;

export default BaseBlock;

方式二:显式定义泛型组件类型

先声明泛型组件的类型,再赋值给forwardRef的结果,逻辑更清晰:

import React from 'react';

interface Props<T> {
  id?: string;
  items?: T[];
  children?: (item: T, index: number) => React.ReactNode;
  parentId?: string;
  contentId?: string[];
}

export type BaseBlockProps<T> = React.PropsWithRef<Props<T>>;

// 定义泛型组件的类型
type BaseBlockComponent = <T>(props: BaseBlockProps<T>) => React.ReactElement | null;

const BaseBlock = React.forwardRef(function BaseBlock<T>(
  { items, children }: React.PropsWithChildren<Props<T>>,
  ref: React.ForwardedRef<HTMLDivElement>
): React.ReactElement | null {
  return (
    <div data-testid="base-block" ref={ref}>
      {items && children && items.map(children)}
    </div>
  );
}) as BaseBlockComponent;

export default BaseBlock;

验证效果

修改完成后,原来的调用代码<BaseBlock<string> items={items}>{renderComp}</BaseBlock>可以正常通过TypeScript类型检查。另外也可以省略显式泛型参数,TypeScript会自动通过items的类型推断出T为string:

<BaseBlock items={items}>{renderComp}</BaseBlock>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:31:04