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

TypeScript如何实现条件Props 传入buttonLabel时强制要求onButtonClick属性

TypeScript 条件约束 Props 实现方案

TypeScript 原生支持这种属性间的依赖约束,不需要额外语法,通过联合类型+互斥属性就能实现你的需求。

实现代码

你可以将 Props 拆分为两种场景的联合类型:

type Props = {
  title: string
} & (
  // 场景1:不传buttonLabel,此时也不能传onButtonClick
  | { buttonLabel?: never; onButtonClick?: never }
  // 场景2:传buttonLabel,此时onButtonClick必传
  | { buttonLabel: string; onButtonClick: () => void }
)

效果验证

// 合法:仅传必填属性
const p1: Props = { title: "页面标题" }

// 合法:同时传buttonLabel和onButtonClick
const p2: Props = {
  title: "页面标题",
  buttonLabel: "提交",
  onButtonClick: () => console.log("点击按钮")
}

// 报错:传了buttonLabel但未传onButtonClick
const p3: Props = { title: "页面标题", buttonLabel: "提交" }

// 报错:传了onButtonClick但未传buttonLabel
const p4: Props = { title: "页面标题", onButtonClick: () => {} }

如果你的需求允许单独传onButtonClick,只需要把第一个分支的onButtonClick?: never改成onButtonClick?: () => void即可。

其他语言的同类特性

这类属性依赖约束本质是代数数据类型(ADT)的应用,很多强类型语言都支持类似能力:

  • Rust:通过带关联值的枚举实现
  • Swift:通过关联值枚举实现
  • Scala:通过样例类联合实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:06:07