TS2531:对象可能为“空" [英] TS2531: Object is possibly 'null'

查看:2153
本文介绍了TS2531:对象可能为“空"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能:-

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

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

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

however on the nativeElement.files[0], I am getting a typescript error, "Object is possibly 'null'". Anyone can help me solve this issue?

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

I tried to declare the nativeElement as a null value, however did not manage to succeed.

感谢您的帮助和时间.

推荐答案

files定义为FileList | null,因此可以为null.您应该检查是否为空(使用if),或者如果您确定它不为空,则使用非空的断言运算符(!);

files is defined to be FileList | null so it can be null. You should either check for null (using a if) or use a not null assertion operator (!) if you are sure it is not 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));

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

Note The not null assertion operator, will not perform any runtime checks, it just tells the compiler you have special information and you know nativeElement.files will not be null at runtime. If nativeElement.files is null at runtime, it will generate at error. This is not the safe navigation operator of other languages.

这篇关于TS2531:对象可能为“空"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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