具有非空值的角度模板编译TS2531错误

具有非空值的角度模板编译TS2531错误

本文介绍了具有非空值的角度模板编译TS2531错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tsconfig.json 中使用"strictNullChecks":true ,当我测试使用异步管道订阅了初始化的Observable的同步值时,出现TS2531错误(对象可能为'null'):

With "strictNullChecks": true in tsconfig.json, when I test a synchronous value subscribing to an initialized Observable with an async pipe, I get a TS2531 error (Object is possibly 'null') :

import {Component} from '@angular/core';
import {Observable, of} from 'rxjs';

@Component({
    selector: 'app-root',
    template: `
        <div *ngIf="(test$|async) === 0">Zero</div>
        <div *ngIf="(test$|async) > 0">Positive</div>
    `,
    styles: []
})
export class AppComponent {
    test$: Observable<number> = of<number>(1);
}

编译错误

有人知道为什么吗?

推荐答案

此功能是通过angular 9的完整模板类型检查与严格的null检查和异步管道相结合而引入的.基本上,异步管道假定一个可观察的对象将是异步的,如果是,则在此期间它会发出null.因此,即使您知道在这种情况下也不会,异步管道的结果可以为null.

this is introduced by angular 9's full template type checks being combined with strict null checks and the async pipe. basically, the async pipe assumes an observable will be asynchronous, and if it is, it emits null in the meantime. So the result of the async pipe CAN be null, even though you know it won't be in this case.

因此,并不是说 test $ 可以为空,而是说(test $ | async)的结果可以为空,严格的null检查意味着您可以不能使用> < 运算符将null与数字进行比较,这就是为什么只有那些(以及等价变体)会向您抛出错误.

so, it's not saying test$ could be null, it's saying the result of (test$ | async) could be null, and strict null checks means you can't compare null to a number with > or < operators which is why only those (and the or equal variants) throw the error at you.

您可以告诉它使用非null断言运算符关闭:

you can tell it to shut up with the non null assertion operator:

<div *ngIf="(test$|async)! > 0">Positive</div>

或者您可以使用新的 $ any 模板转换功能来禁用类型检查:

or you can make use of the new $any template cast function to disable type checking:

<div *ngIf="$any(test$|async) > 0">Positive</div>

或者,如果愿意,可以通过在tsconfig角度编译器选项中将 fullTemplateTypeCheck 设置为false来禁用整个应用程序的模板类型检查

or if you wish, you can disable template type checking app wide by setting fullTemplateTypeCheck to false in your tsconfig angular compiler options

更多信息: https://angular.io/guide/template-typecheck#strict-null-checks

这篇关于具有非空值的角度模板编译TS2531错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:18