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

如何用TypeScript实现React组件基于isLoading的可选Props

解决方案:用TypeScript联合类型实现条件式Props

要实现当isLoading为true时让src、description可选,核心思路是用联合类型拆分两种状态的Props定义,让TypeScript根据isLoading的布尔值自动推断其他Props的必填性。

步骤1:拆分Props类型

先定义基础的非加载状态所需的Props,再通过联合类型组合两种状态:

// 定义非加载状态下的必填Props
interface BaseImageProps {
  src: string;
  description: string;
}

// 联合类型:加载状态时其他Props可选,非加载状态时必填
type CustomImageComponentProps = 
  | { isLoading: true } & Partial<BaseImageProps>
  | { isLoading: false } & BaseImageProps;

步骤2:更新组件定义

把组件的Props类型替换为上面的联合类型,并在组件内部利用TypeScript的类型收窄特性,确保非加载状态下能安全访问src和description:

export const MyCustomImage = ({ isLoading, src, description }: CustomImageComponentProps) => {
  if (isLoading) {
    return <Shimmer />;
  }

  // 这里TypeScript会自动知道isLoading为false,src和description必然存在
  return (
    <div>
      <img src={src} alt={description} />
      <p>{description}</p>
    </div>
  );
};

为什么这能生效?

  • 当传入isLoading: true时,TypeScript会匹配联合类型的第一个分支,此时src和description是可选的(因为用了Partial工具类型)。
  • 当传入isLoading: false时,TypeScript会匹配第二个分支,此时src和description是必填项,不传会直接报错。
  • 在组件内部通过if (isLoading)判断后,TypeScript会自动收窄类型,非加载分支里可以安全使用src和description,无需额外的可选链或空值检查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:25:09