类型定义中的感叹号 [英] Exclamation Mark in type definition

查看:266
本文介绍了类型定义中的感叹号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我偶然发现了Angular的 ContentChildren装饰器.在第一个代码示例中,使用以下语法:

Currently I stumbled upon the ContentChildren decorator of Angular. In the first code example the following syntax is used:

import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core';

@Directive({selector: 'child-directive'})
class ChildDirective {
}

@Directive({selector: 'someDir'})
class SomeDir implements AfterContentInit {
  @ContentChildren(ChildDirective) contentChildren !: QueryList<ChildDirective>;  // this line is relevant

  ngAfterContentInit() {
    // contentChildren is set
  }
}

请注意在@ContentChildren(ChildDirective) contentChildren变量定义之后的感叹号和冒号.在此StackOverflow线程中,我发现了在访问变量或对象属性时,可以将该语法用作非null断言运算符".

Note the exclamation mark followed by a colon right after the @ContentChildren(ChildDirective) contentChildren variable definition. In this StackOverflow thread I discovered that this syntax can be used as a "non-null assertion operator" when accessing a variable or object property.

我的问题是,类型定义之前的感叹号是否具有与正常情况下完全相同的含义.它只是简单地说TypeScript编译器:好吧,不用担心null或未定义",还是在此上下文中此语法还有其他特定含义?

My question is now whether the exclamation mark before a type definition has exactly the same meaning like in a normal context. Does it simply say the TypeScript compiler: "Okay, don't worry about null or undefined", or does this syntax have another specific meaning in this context?

推荐答案

我的问题是,类型定义之前的感叹号是否具有与正常情况下完全相同的含义.

My question is now whether the exclamation mark before a type definition has exactly the same meaning like in a normal context.

不,这实际上不是一回事,在这种情况下,它所做的事情有所不同.通常,当您声明成员(类型中不包含undefined)时,必须直接或在构造函数中对其进行初始化.如果在名称后添加!,TypeScript将忽略此名称,并且如果您不立即对其进行初始化,则不会显示错误:

No that's actually not the same thing, in this context it does something different. Normally when you declare a member (which doesnt' include undefined in it's type) it has to be initialized directly or in the constructor. If you add ! after the name, TypeScript will ignore this and not show an error if you don't immediately initialize it:

class Foo {
  foo: string; // error: Property 'foo' has no initializer and is not definitely assigned in the constructor.
  bar!: string; // no error
}

同样的事情实际上也适用于局部变量:

The same thing actually applies to local variables as well:

let foo: string;
let bar!: string;

console.log(foo); // error: Variable 'foo' is used before being assigned.
console.log(bar); // no error

游乐场

这篇关于类型定义中的感叹号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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