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

带剩余参数的TypeScript React泛型分页组件类型推断问题如何解决

问题修复方案

错误原因

报错的核心是 TypeScript 静态分析阶段无法证明「用户传入的剩余属性 + 组件内部补全的CommonContainerProps属性」刚好完全匹配泛型TContainerProps的约束。
因为TContainerProps是CommonContainerProps的子类型,外部可以传入任意符合约束的子类型实现,TS 无法在静态阶段推导两者组合后的结果完全匹配子类型的全部要求,所以抛出了类型不兼容的错误。

修复方法

你只需要在渲染Container时,将合并后的属性断言为TContainerProps即可,逻辑上你已经保证了属性的完整性,这个断言是完全安全的。
修改ConnectedComponent的render部分代码:

export class ConnectedComponent<
  TContainerProps extends CommonContainerProps
> extends React.PureComponent<ConnectedComponentProps<TContainerProps>> {
  render() {
    const {
      path,
      pagination,
      container,
      containerRef,
      ...containerProps
    } = this.props;

    const Container = container;

    return (
      <Container
        {...{
          ...containerProps,
          ref: containerRef,
          itemCount: 10,
          onItemsRendered: console.log,
          width: 100,
          height: 100
        } as TContainerProps}
      />
    );
  }
}

效果验证

修改后原有使用逻辑完全不变,同时类型能力完全符合预期:

  • 可以自动推断传入的container组件的属性类型,非公共属性会要求用户正常传入(比如示例中的className)
  • CommonContainerProps中定义的公共属性不会出现在ConnectedComponent的入参提示中,由组件内部自动注入
  • 原有类型报错完全消失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:36:03