You need to enable JavaScript to run this app. Typescript如何实现条件必填参数:属性为true时关联字段强制必填
优惠活动
大模型
产品
解决方案
定价
更多

Typescript如何实现条件必填参数:属性为true时关联字段强制必填

Typescript 实现参数条件必填的解决方案

你可以通过**可辨识联合类型(Discriminated Union)**实现该需求,核心思路是把不同参数状态的类型拆分为独立分支,再通过联合类型合并,TS 会自动根据pets的取值推导关联字段的必填规则。

具体实现代码

// 抽离所有场景下都必填的公共字段
type BasePersonInfo = {
  name: string;
  age: number;
}

// 无宠物场景:pets 不传或为false,不允许出现 petNames(可选调整)
type NoPetsInfo = BasePersonInfo & {
  pets?: false;
  petNames?: never;
}

// 有宠物场景:pets 为true,petNames 强制必填
type HasPetsInfo = BasePersonInfo & {
  pets: true;
  petNames: string[];
}

// 合并两种场景得到最终的参数类型
type PersonInfo = NoPetsInfo | HasPetsInfo;

const recordPersonInfo = (options: PersonInfo) => {
  database.save(options); 
}

校验效果示例

  • 合法传参(TS 无报错):
// 场景1:不涉及宠物
recordPersonInfo({ name: '张三', age: 20 })

// 场景2:显式声明没有宠物
recordPersonInfo({ name: '李四', age: 22, pets: false })

// 场景3:有宠物,同时提供宠物名
recordPersonInfo({ name: '王五', age: 25, pets: true, petNames: ['旺财', '咪咪'] })
  • 非法传参(TS 会自动抛出类型错误):
// 错误:pets为true但未提供petNames
recordPersonInfo({ name: '赵六', age: 23, pets: true })

// 错误:pets为false时不允许传递petNames(由petNames?: never限制,不需要该规则可删除该行)
recordPersonInfo({ name: '孙七', age: 24, pets: false, petNames: ['阿黄'] })

可选调整说明

如果允许pets为false时也可以传递petNames,只需要把NoPetsInfo中的petNames?: never改为petNames?: string[]即可,不会影响pets为true时的必填校验规则。

内容的提问来源于stack exchange,提问作者TJBlackman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 17:57:03