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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:36:04