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

TypeScript:如何实现多类型对象的属性存在性类型判断

TypeScript联合类型收窄的正确做法

你遇到的问题是因为TypeScript无法将独立变量isTypeA的布尔值和example.b的类型关联起来,导致无法自动收窄联合类型。下面是几种正确的解决方式:

1. 直接在条件分支中检查属性

不用中间变量,直接在三元运算符里判断example.b.c的值,编译器能直接跟踪类型关联:

const example: ExampleType = {
  a: 'hello',
  b: {c: "typeA", d: "hello world"},
};

const result = example.b.c === 'typeA' ? example.b.d : example.b.e; // 无报错

2. 使用自定义类型守卫函数

如果需要复用类型判断逻辑,可以写一个带类型谓词的守卫函数,明确告诉编译器判断后的类型:

type ExampleInnerTypeA = {
  c: "typeA";
  d: string;
}

type ExampleInnerTypeB = {
  c: "typeB";
  e: string;
}

type ExampleType = {
  a: string,
  b: ExampleInnerTypeA | ExampleInnerTypeB;
}

// 自定义类型守卫
function isTypeA(obj: ExampleInnerTypeA | ExampleInnerTypeB): obj is ExampleInnerTypeA {
  return obj.c === 'typeA';
}

const example: ExampleType = {
  a: 'hello',
  b: {c: "typeA", d: "hello world"},
};

const result = isTypeA(example.b) ? example.b.d : example.b.e; // 无报错

3. 类型断言(不推荐)

如果一定要用中间变量,可以手动用类型断言强制指定类型,但这种方式会跳过TypeScript的类型检查,存在运行时风险,仅在你能100%确定类型时使用:

const example: ExampleType = {
  a: 'hello',
  b: {c: "typeA", d: "hello world"},
};

const isTypeA = example.b.c === 'typeA';
const result = isTypeA ? (example.b as ExampleInnerTypeA).d : (example.b as ExampleInnerTypeB).e;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:41:03