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

Angular/TypeScript中如何调用联合类型的test变量?

处理可选联合类型test的访问逻辑

你定义的test是可选联合类型,既可能是布尔值,也可能是键为TestEnum枚举值的对象。在组件中访问时,需要通过类型收窄让TypeScript明确当前test的具体类型,才能安全调用。

方法一:用typeof做基础类型判断

这是最直接的方式,通过typeof区分布尔值和对象类型:

// 假设你拿到了目标常量(TEST_1或TEST_2)
const currentData = TEST_1; // 可替换为TEST_2

// 先处理test为undefined的情况
if (currentData.test !== undefined) {
  // 判断是否为布尔值类型
  if (typeof currentData.test === 'boolean') {
    // 直接当作布尔值使用,比如组件条件渲染
    // {currentData.test && <div>布尔值为true时显示</div>}
    console.log('布尔值:', currentData.test);
  } else {
    // 此时TypeScript自动推断test为枚举键对象,可安全访问枚举属性
    // {currentData.test[TestEnum.Value2] && <div>Value2对应状态为true时显示</div>}
    console.log('Value1状态:', currentData.test[TestEnum.Value1]);
    console.log('Value2状态:', currentData.test[TestEnum.Value2]);
  }
}

方法二:自定义类型守卫(适合复杂场景)

如果需要在多处复用类型判断逻辑,可以写一个自定义类型守卫函数:

// 定义类型守卫,判断是否为枚举键对象
function isTestEnumObject(test: boolean | { [key in TestEnum]: boolean }): test is { [key in TestEnum]: boolean } {
  return typeof test === 'object' && test !== null;
}

// 使用示例
const currentData = TEST_2;
if (currentData.test !== undefined) {
  if (isTestEnumObject(currentData.test)) {
    console.log('Value2状态:', currentData.test[TestEnum.Value2]);
  } else {
    console.log('布尔值:', currentData.test);
  }
}

注意事项

  • 你提供的TEST_1中,对象里重复声明了[TestEnum.Value1]键,最终只会保留最后一次赋值的true,实际代码里要避免重复键的写法。
  • 因为test是可选属性,必须先判断test !== undefined,或者用可选链currentData.test?.xxx(但对象场景下仍需类型收窄才能访问枚举键)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:07:21