我可以在 Angular 模板中进行类型缩小吗?

Cod*_*rer 7 typescript angular

我有一个将业务对象作为输入的组件。在此组件的模板中,我想通过检查仅存在于业务对象的某些子类上的属性值来有条件地呈现某些内容。

export class Thing { public foo: string; }
export class SubThing extends Thing { public bar: number; }

// ...
export class MyComponent {
  @Input() thing: Thing;
}
Run Code Online (Sandbox Code Playgroud)
<!-- template file -->
{{ thing.foo }}
<div *ngIf="thing?.bar > 10">Conditional content...</div>
Run Code Online (Sandbox Code Playgroud)

这曾经按编写的方式工作,因为编译器对模板中的类型检查不是很严格。最近这开始与 AOT 编译器中断(不确定确切时间),因为严格来说,thing?.bar当编译器认为thing只是 a时无效Thing,并且不能肯定地说它是SubThing.

我想说类似的话,*ngIf="thing instanceof SubThing && thing?.bar > 10"但我不能instanceof在模板本身中使用。有没有其他方法可以检查thing模板中的类型,以便编译器停止抱怨?(我通过指定我的 Input as 使构建再次工作,any但当然如果可能的话,我想让我的类型检查。)

Cod*_*rer 6

显然,编译器尊重User Defined Type Guards。我只需要在我的组件中定义一个方法:

export class MyComponent {
  // ...
  /** @internal */ isSubThing(t: Thing): t is SubThing {
    return t instanceof SubThing;
  }
}
Run Code Online (Sandbox Code Playgroud)
<!-- template file -->
{{ thing.foo }}
<div *ngIf="isSubThing(thing) && thing?.bar > 10">
  Conditional content...
</div>
Run Code Online (Sandbox Code Playgroud)

  • 从 Angular 10.0.7 开始,这似乎不再起作用 (3认同)