angular - ! : (bang colon) notation in Angular

标签 angular typescript

我发现在 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,所以它不应该被设置为 nullundefined。同时,它并没有在构造函数中进行初始化,所以会得到一个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/

相关文章:

angular - 在Angular中按对象属性对元素进行分组

typescript - 如何在 TypeScript 中手动柯里化(Currying)一个函数?

angularjs - 没有导出的成员/Node 模块

javascript - 在 Typescript 对象类中保留原始属性

javascript - 如何在 Angular2 中使用 Dojo?

javascript - 如何在 Angular 中构建延迟加载侧边栏?

Angular Universal Bundle 不断加载空白页面

typescript - TypeScript 如何推断回调参数类型

extjs - ExtJS 5 的 TypeScript 定义

Angular 5 - 带对象的表单控件