TS2531: Object is possibly 'null'

前端 未结 4 1938

I have the following function:-

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

    this.photoService.upload(this.ve         


        
相关标签:
4条回答
  • 2020-12-11 00:28

    TypeScript 3.7 got released in 11/2019. Now "Optional Chaining" is supported, this is the easiest and most secure way of working with potentially null-able values:

    You simply write:

    nativeElement?.file?.name
    

    Note the Question-Mark! They check for null/undefined and only return the value, if none of the properties (chained with dots) is null/undefined.

    Instead of

    if(nativeElement!=null && nativeElement.file != null) {
      ....
    }
    

    But imagine something more complex like this: crm.contract?.person?.address?.city?.latlang that would otherwise a lot more verbose to check.

    0 讨论(0)
  • 2020-12-11 00:28

    Using the answer from Markus which referenced optional chaining, I solved your problem by casting nativeElement to HTMLInputElement and then accessing the 0th file by using .item(0) with the optional chaining operator ?.

    uploadPhoto() {
        var nativeElement = this.fileInput.nativeElement as HTMLInputElement
    
        this.photoService.upload(this.vehicleId, nativeElement?.files?.item(0))
            .subscribe(x => console.log(x));
    }
    
    0 讨论(0)
  • 2020-12-11 00:30

    If you are sure that there is a file in all cases. You need make compiler to be sure.

    (nativeElement.files as FileList)[0]
    
    0 讨论(0)
  • 2020-12-11 00:35

    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));
    

    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.

    0 讨论(0)
提交回复
热议问题