如何在TypeScript中实现支持多层级嵌套的RequireOnlyOne类型
实现方案
我们可以直接嵌套复用已有的RequireOnlyOne类型,先后对二级属性、一级属性做单属性互斥约束即可满足需求。
1. 复用基础的RequireOnlyOne类型
type RequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> & { [K in Keys]-?: Required<Pick<T, K>> & Partial<Record<Exclude<Keys, K>, undefined>> }[Keys]
2. 原有MenuItems接口定义
export interface MenuItems { firstLevel: { secondLevel: ['one', 'two'] }; anotherFirstLevel: { anotherSecondLevel: ['one', 'two'], oneMoreSecondLevel: null }; }
3. 组合生成目标类型customType
// 第一步:先约束每个一级属性对应的二级对象只能存在1个二级属性 type SecondLevelConstrained = { [K in keyof MenuItems]: RequireOnlyOne<MenuItems[K]> } // 第二步:约束顶层对象只能存在1个一级属性 type customType = RequireOnlyOne<SecondLevelConstrained>
4. 效果验证
// 正常通过类型校验 const workingObject: customType = { firstLevel: { secondLevel: ['one', 'two'] } } // 触发报错:同时存在2个一级属性 const errorObject: customType = { firstLevel: { secondLevel: ['one', 'two'] }, anotherFirstLevel: { anotherSecondLevel: ['one', 'two'] } } // 触发报错:一级属性下同时存在2个二级属性 const anotherErrorObject: customType = { anotherFirstLevel: { anotherSecondLevel: ['one', 'two'], oneMoreSecondLevel: null } }
内容的提问来源于stack exchange,提问作者Cristian Blandon
相关产品推荐
相关产品推荐

