TS2531:对象可能是'null'

Joh*_*ann 12 typescript angular

我有以下功能: -

uploadPhoto() {
    var nativeElement: HTMLInputElement = this.fileInput.nativeElement;

    this.photoService.upload(this.vehicleId, nativeElement.files[0])
        .subscribe(x => console.log(x));
}
Run Code Online (Sandbox Code Playgroud)

但是在nativeElement.files [0]上,我收到了一个打字稿错误,"对象可能是'null'".有人可以帮我解决这个问题吗?

我试图将nativeElement声明为null值,但是没有成功.

谢谢你的帮助和时间.

Mar*_*kus 26

TypeScript 3.7 于 11/2019 发布。现在支持“可选链”,这是处理可能为空的值的最简单和最安全的方法:

你只需写:

nativeElement?.file?.name
Run Code Online (Sandbox Code Playgroud)

注意问号!他们检查空/未定义,如果没有任何属性(用点链接)为空/未定义,则仅返回值。

代替

if(nativeElement!=null && nativeElement.file != null) {
  ....
}
Run Code Online (Sandbox Code Playgroud)

但是想象一下像这样更复杂的事情:crm.contract?.person?.address?.city?.latlang否则检查起来会更加冗长。

  • 很有意思!有什么缺点?似乎是一个进步。当然总是有利有弊。 (2认同)

Nit*_*sht 18

除了上面提到的所有答案之外,如果用户不希望在其应用程序中进行严格的空检查,我们可以简单地禁用文件strictNullChecks中的属性tsconfig.json

{
 ...
 "angularCompilerOptions": {
 "strictNullChecks": false,
 ...
 }
}
Run Code Online (Sandbox Code Playgroud)


Tit*_*mir 12

files被定义为FileList | null可以null.如果您确定它不为null,则应检查null(使用a if)或使用非null断言运算符(!);

if(nativeElement.files != null) {
    this.photoService.upload(this.vehicleId, nativeElement.files[0])
        .subscribe(x => console.log(x));
}

//OR
this.photoService.upload(this.vehicleId, nativeElement.files![0])
    .subscribe(x => console.log(x));
Run Code Online (Sandbox Code Playgroud)

注意 not null断言运算符不会执行任何运行时检查,它只是告诉编译器您有特殊信息,并且您知道nativeElement.files在运行时不会为null.如果nativeElement.files在运行时为null,则会生成错误.这不是其他语言的安全导航操作员.


Vay*_*rex 5

如果您确定在所有情况下都有一个文件。你需要 make compiler 来确定。

(nativeElement.files as FileList)[0]
Run Code Online (Sandbox Code Playgroud)