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

Angular 2中如何让变量支持两种模型类型?无需使用any

解决方法

首先纠正你的语法错误:TypeScript里表示联合类型要用竖线|,而不是逻辑或的||,所以变量的正确声明方式是:

private exampleVariable: Model1 | Model2;

这样变量就可以接收Model1或Model2类型的实例了。

接下来要注意:直接访问联合类型变量的属性时,TypeScript只允许访问两个类型共有的属性(比如这里的id)。如果要访问各自独有的属性(比如Model1的name、Model2的parentId),需要用类型守卫来做类型判断,确保类型安全:

方法1:用in操作符做类型守卫

if ('name' in this.exampleVariable) {
  // 这里TypeScript会自动推断this.exampleVariable是Model1类型
  console.log(this.exampleVariable.size);
} else {
  // 这里会自动推断是Model2类型
  console.log(this.exampleVariable.title);
}

方法2:给接口添加类型标识(更直观)

给两个接口加一个字面量类型的字段,用来明确区分类型:

interface Model1 {
  type: 'model1'; // 新增类型标识
  id: number;
  name: string;
  size: string;
  count: number;
  children: Model2[];
}

interface Model2 {
  type: 'model2'; // 新增类型标识
  id: number;
  parentId: number
  title: string;
  subtitle: string;
  publisher: string;
}

之后判断类型会更清晰:

if (this.exampleVariable.type === 'model1') {
  console.log(this.exampleVariable.name);
} else {
  console.log(this.exampleVariable.parentId);
}

这两种方法都不需要用any类型,能完全保留TypeScript的类型检查能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:45:39