在阅读 Angular 2 源代码时,我遇到了NgForOfContext<T>
哪些源代码可以在这里的官方存储库中找到,下面是引起兴趣的部分。
特别是以下语法是我在纯Javascript和Typescript中从未见过的:
private _applyChanges(changes: IterableChanges<T>) {
const insertTuples: RecordViewTuple<T>[] = [];
changes.forEachOperation(
(item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
if (item.previousIndex == null) {
const view = this._viewContainer.createEmbeddedView(
this._template, new NgForOfContext<T>(null !, this.ngForOf, -1, -1), currentIndex);
const tuple = new RecordViewTuple<T>(item, view);
insertTuples.push(tuple);
} else if (currentIndex == null) {
this._viewContainer.remove(adjustedPreviousIndex);
} else {
const view = this._viewContainer.get(adjustedPreviousIndex) !;
this._viewContainer.move(view, currentIndex);
const tuple = new RecordViewTuple(item, <EmbeddedViewRef<NgForOfContext<T>>>view);
insertTuples.push(tuple);
}
});
我说的是排队null !
:
this._template, new NgForOfContext<T>(null !, this.ngForOf, -1, -1), currentIndex);
第一个参数为 null,后跟逻辑上的 not (!(。为了理解这段代码,我已经仔细检查了,据我所知,null
是一个原始的Javascript(和TS(类型,有一个null !
是没有意义的。此外,如果返回true
!null
(不为 null(,这将更具语法意义
为了确保我错了,我试图编译它,但令我惊讶的是,它失败了。它抱怨意外(
现在,显然Angular有效。我们都知道这一点。因此,我一定错过了什么。祈祷,解开这个杀手之谜...
这被称为非空断言运算符,当我们有一个可以为 null 的值来断言它不为空时
使用它var nullable: string | null = null;
var nonNullable: string = "";
nonNullable = nullable // Error
nonNullable = nullable! // Ok, we asserted it is not null
在这种情况下,它被用来(相当违反直觉(断言null
不为空
nonNullable = null! // Ok, we assert null is not null
游乐场链接