我发现在 Angular Deprecation docs 中使用了 !:
符号.
@Input() tpl !: TemplateRef<any>;
@ContentChild(TemplateRef) inlineTemplate !: TemplateRef<any>;
发现相同here as well .
@Input() id !: string;
我不确定 Angular 中 !:
符号的术语(或背后的概念)是什么。谷歌搜索对我帮助不大。试过SymbolHound和 Angular Docs 一样,但都是徒劳的。
如果有人可以阐明它,比如它是如何工作的,或者至少分享文档链接,那将会很有帮助。
最佳答案
如果你有 strictNullChecks
然后你用 @Input
装饰的任何东西通常都会报错。例如……
public class MyComponent {
@Input()
public myField: string;
constructor() {}
}
这将导致 TS 提示。这是因为 myField
没有被声明为 nullable,所以它不应该被设置为 null
或 undefined
。同时,它并没有在构造函数中进行初始化,所以会得到一个undefined
的初始值。
通常情况下,这很好。我们知道 Angular 会在构建后不久设置值。如果我们将字段标记为可空 public myField: string?
那么我们将不得不在尝试使用它时到处处理 this field may be null
错误。
因此,作为妥协,我们在字段声明中抛出一个 !
来告诉 Typescript “我知道这看起来像是被初始化为 null/undefined 但相信我,我会处理好的它”。
关于angular - ! : (bang colon) notation in Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58073841/