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

TypeScript中如何根据watchOverflow值控制removeOverflowing的必填性?

实现方法

要实现「当watchOverflow为true时,removeOverflowing必须传入」的约束,直接用TypeScript的区分联合类型就能搞定,具体写法如下:

// 先把所有公共属性抽出来,避免重复代码
type CommonProps = {
  dellSelectedOption: (id: string, idOptions: string[]) => void;
  ownFilterData: Array<ActiveFilterAndPredFilterDataType>;
  children: React.ReactNode;
  overflowLimit: number;
  parentName: string;
};

// 第一种场景:watchOverflow设为true,此时removeOverflowing必须传
type WatchOverflowEnabledProps = CommonProps & {
  watchOverflow: true;
  removeOverflowing: (ids: { [x: string]: string[] }[]) => void;
};

// 第二种场景:watchOverflow设为false,此时removeOverflowing可传可不传
type WatchOverflowDisabledProps = CommonProps & {
  watchOverflow: false;
  removeOverflowing?: (ids: { [x: string]: string[] }[]) => void;
};

// 最终的PropsType是两种场景的联合类型
type PropsType = WatchOverflowEnabledProps | WatchOverflowDisabledProps;

实际效果

  • 当你给watchOverflow传true时,TypeScript会自动检查removeOverflowing是否存在,没传就直接报错;
  • 当watchOverflow传false时,removeOverflowing传不传都可以,不会有强制要求。

这样就精准满足了你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:55:21