!:(冒号)在Angular中的表示法 [英] !: (bang colon) notation in Angular

查看:220
本文介绍了!:(冒号)在Angular中的表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现找到了相同的.

@Input() id !: string;

我不确定Angular中!:表示法的术语(或背后的概念)是什么.谷歌搜索对我没有多大帮助.尝试 SymbolHound 和Angular Docs相同,但都是徒劳的.

如果有人可以阐明它的功能(例如它的功能)或至少共享文档链接,这将很有帮助.

解决方案

如果打开strictNullChecks,则用@Input装饰的任何东西通常都会抱怨.例如...

public class MyComponent {

  @Input()
  public myField: string;

  constructor() {}

}

这将导致TS投诉.这是因为myField尚未声明为可为空,因此永远不应将其设置为nullundefined.同时,它没有在构造函数中初始化,因此它将获得初始值undefined.

通常,这很好.我们知道,Angular将在构造后不久设置该值.如果我们将该字段标记为可为空的public myField: string?,则在尝试使用它时,我们将不得不在整个地方处理this field may be null错误.

因此,作为一种妥协,我们在字段声明上抛出!来告诉Typescript我知道这看起来像已被初始化为null/undefined,但请相信我,我会处理的."

I found !: notation being used in Angular Deprecation docs.

@Input() tpl !: TemplateRef<any>;
@ContentChild(TemplateRef) inlineTemplate !: TemplateRef<any>;

Found the same here as well.

@Input() id !: string;

I'm not sure what is the terminology (or concept behind) for !: notation in Angular. Googling didn't help me much. Tried SymbolHound and Angular Docs for the same, but all in vain.

It'd be helpful if someone could shed some light on it, like how does it function, or share the doc link at the very least.

解决方案

If you have strictNullChecks on then anything you decorate with @Input will usually complain. For example...

public class MyComponent {

  @Input()
  public myField: string;

  constructor() {}

}

This will lead to TS complaining. This is because myField has not be declared nullable so it should never be set to null or undefined. At the same time, it is not initialized in the constructor, so it will get an initial value of undefined.

Normally, this is fine. We know that Angular will set the value shortly after construction. If we mark the field nullable public myField: string? then we will have to deal with this field may be null errors all over the place when we try and use it.

So, as a compromise, we throw a ! on the field declaration to tell Typescript "I know this looks like it is getting initialized to null/undefined but trust me, I will take care of it".

这篇关于!:(冒号)在Angular中的表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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