如何在TypeScript interface中定义content或children二选一的字段?
TypeScript 实现互斥可选属性方案
错误写法说明
你尝试的[content | children]: ReactElement写法不符合TypeScript语法规则,方括号是索引签名的专属语法,无法实现「两个属性二选一存在」的需求。
具体实现方案
方案1:联合+交叉类型实现互斥(最常用)
通过拆分公共属性和差异化属性,配合交叉类型和never限定实现严格互斥,不允许同时传content和children,也不允许两个都不传:
// 抽离所有公共属性 interface IModalBaseProps { isOpen: boolean; type: 'basic'; options?: IModalOption; } // 联合两种属性场景,用never限定互斥 type IModalProps = IModalBaseProps & ( | { content: React.ReactElement; children?: never } | { children: React.ReactElement; content?: never } )
如果不需要严格互斥,只要求至少存在其中一个属性,可以去掉never限定:
type IModalProps = IModalBaseProps & ( | { content: React.ReactElement } | { children: React.ReactElement } )
方案2:封装通用互斥工具类(适合复用)
如果项目中多处需要用到属性互斥的能力,可以封装通用的XOR工具类型复用:
// 通用互斥工具类型:T和U的属性只能二选一存在 type XOR<T, U> = (T & Partial<Record<keyof U, never>>) | (U & Partial<Record<keyof T, never>>) interface IModalBaseProps { isOpen: boolean; type: 'basic'; options?: IModalOption; } type IModalProps = IModalBaseProps & XOR< { content: React.ReactElement }, { children: React.ReactElement } >
组件内使用示例
在组件内部可以直接用in操作符收窄类型,TypeScript会自动推导正确的属性类型:
const Modal = (props: IModalProps) => { const renderContent = 'content' in props ? props.content : props.children; // 后续组件逻辑 }
内容的提问来源于stack exchange,提问作者Hyeon__
相关产品推荐
相关产品推荐

