Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

angular - TS2531: Object is possibly 'null'

I have the following function:-

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

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

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

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

Thanks for your help and time.

question from:https://stackoverflow.com/questions/49431880/ts2531-object-is-possibly-null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

files is defined to be FileList | null so it can be null.

You should either check for null (using an if) or use a "Non-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));

Note:

The "Non-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 an error. This is not the safe navigation operator of other languages.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...