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

TypeScript中如何正确声明FooBarLoaderProps以传递可选Props?

解决方案:通过交叉类型与Omit实现Props透传的类型声明

你的核心问题在于没有正确将LoadingSpinner的可选Props合并到FooBarLoaderProps中,同时处理好Loader自身负责传递的属性(比如error)。以下是正确的实现方式:

1. 拆分并合并类型

首先把FooBarLoader自己的属性和需要透传的LoadingSpinner属性分开,通过交叉类型&和Omit工具类型排除掉Loader内部已经处理的属性:

import type { ReactNode } from 'react';

// 定义FooBarLoader自身的专属属性
type FooBarLoaderOwnProps = {
  action: () => void; // 替换模糊的Function,用具体函数类型更严谨
  selector: (state: MyProjectState) => MightError<string>;
  children?: ReactNode;
};

// 合并专属属性与LoadingSpinner的剩余可选Props(排除Loader自己处理的error和children)
type FooBarLoaderProps = FooBarLoaderOwnProps & Omit<LoadingSpinnerProps, 'error' | 'children'>;

2. 调整组件参数接收

修改FooBarLoader的参数解构,剩余的props会自动包含LoadingSpinner的所有可选属性(比如label):

const FooBarLoader = ({
  action,
  children = undefined,
  selector,
  ...props // 现在props会自动包含label等LoadingSpinner的可选属性
}: FooBarLoaderProps) => {
  const error = useSelector(compose(getErrorFromState, selector));
  
  return (
    <LoadingSpinner
      error={error} // Loader内部生成并传递error,无需外部传入
      {...props} // 透传label等所有LoadingSpinner的剩余属性
    >
      {children}
    </LoadingSpinner>
  );
};

为什么之前的方法无效?

  • 手动声明单个属性(比如label)会导致重复维护,且无法覆盖LoadingSpinner的所有可选Props;
  • 使用Partial<{label:string}>只能覆盖单个属性,无法同步LoadingSpinner的其他属性变更;
  • 原来的props: {}是一个空类型,TypeScript无法识别透传的属性类型,自然会报错。

额外优化建议

  • 避免使用模糊的Function类型,换成具体的函数签名(比如() => Promise<void>如果action是异步的),提升类型检查的严谨性;
  • 如果LoadingSpinner后续新增可选Props,FooBarLoaderProps会自动同步,无需手动修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:05:25