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
相关产品推荐
相关产品推荐

