我可以在 Angular 模板中进行类型缩小吗? [英] Can I do type-narrowing in an Angular template?

查看:32
本文介绍了我可以在 Angular 模板中进行类型缩小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

export class Thing { public foo: string;}export class SubThing extends Thing { public bar: number;}//...导出类 MyComponent {@Input() 东西:东西;}

<小时>

{{thing.foo }}<div *ngIf="thing?.bar > 10">条件内容...</div>

这曾经像写的那样工作,因为编译器对模板中的类型检查不是很严格.最近这开始与 AOT 编译器发生冲突(不确定确切时间),因为严格来说,当编译器认为 thing 只是一个 时,thing?.bar 是无效的>Thing,并且不能肯定地说它是一个 SubThing.

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

解决方案

显然编译器尊重 用户定义的类型防护.我只需要在我的组件中定义一个方法:

导出类 MyComponent {//.../** @internal */isSubThing(t: Thing): t is SubThing {return t instanceof SubThing;}}

<小时>

{{thing.foo }}<div *ngIf="isSubThing(thing) && thing?.bar > 10">有条件的内容...

I have a component that takes a business object as an Input. In the template for this component, I want to conditionally render some content by checking the value of a property that only exists on some subclasses of the business object.

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

// ...
export class MyComponent {
  @Input() thing: Thing;
}


<!-- template file -->
{{ thing.foo }}
<div *ngIf="thing?.bar > 10">Conditional content...</div>

This used to work as written because the compiler wasn't very strict about type checking in the templates. Recently this started breaking with the AOT compiler (not sure exactly when) because, strictly speaking, thing?.bar is not valid when the compiler thinks thing is just a Thing, and can't say for certain that it's a SubThing.

I would like to say something like *ngIf="thing instanceof SubThing && thing?.bar > 10" but I can't use instanceof in the template itself. Is there some other way I can check the type of thing from the template, such that the compiler stops complaining? (I got the build working again by specifying my Input as any but of course I'd like to get my type checking back if possible.)

解决方案

Apparently the compiler respects User Defined Type Guards. I just have to define a method in my component:

export class MyComponent {
  // ...
  /** @internal */ isSubThing(t: Thing): t is SubThing {
    return t instanceof SubThing;
  }
}


<!-- template file -->
{{ thing.foo }}
<div *ngIf="isSubThing(thing) && thing?.bar > 10">
  Conditional content...
</div>

这篇关于我可以在 Angular 模板中进行类型缩小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆