TypeScript如何在传入指定可选prop时将原有必填prop改为非必填?
可以通过TypeScript的可辨识联合类型原生特性实现,无需额外依赖,具体实现方式如下:
第一步:定义条件Props类型
把原本的单接口拆分为两种互斥的场景联合,同时可以抽离公共props复用:
import React from 'react'; // 抽离所有场景通用的公共属性 type CommonModalProps = { children: React.ReactNode; title?: string; visible?: boolean; // 其他通用属性可继续补充 } // 联合两种互斥的props规则 type ModalProps = CommonModalProps & ( // 场景1:未传入自定义footer,onClose为必填项 | { footer?: undefined; onClose: () => void; } // 场景2:传入了自定义footer,onClose为可选项 | { footer: React.ReactElement; onClose?: () => void; } )
第二步:组件使用效果
配置完成后TypeScript会自动校验props规则:
- 不传
footer时,必须传入onClose,漏传会直接抛出类型错误 - 传入
footer时,onClose可传可不传,你之前的兼容写法可以直接简化为:
<Modal footer={renderFooterWhichHasItsOwnCloseMethod()} > {children} </Modal>
拓展配置
如果需要严格禁止传入footer的同时传入onClose,只需要把第二种场景的onClose声明为never即可:
type ModalProps = CommonModalProps & ( | { footer?: undefined; onClose: () => void; } | { footer: React.ReactElement; onClose?: never; // 存在footer时禁止传入onClose } )
内容的提问来源于stack exchange,提问作者Aaron Balthaser
相关产品推荐
相关产品推荐

