Home > Blockchain >  how to fix this "object is possibly null" error in typescript without disables strictNullC
how to fix this "object is possibly null" error in typescript without disables strictNullC

Time:03-30

here is my typescript code :

const form  = document.querySelector('form');


if (form != null ) {
    const data = new FormData(form);
    for (const pair of data) {
        console.log(pair);
    }
    // OR
    for (const pair of data.entries()) {
        console.log(pair);
    }
}

document.getElementById("form_file")!.onchange= function(e: Event) {
    let file = (<HTMLInputElement>e.target).files[0];
    }

I've tried :

let file = (<HTMLInputElement>e?.target)?.files[0];

and

let file = (<HTMLInputElement>e!.target)!.files[0];

how to make it works without using the disables strictNullChecks option in tsconfig ?

Regards

CodePudding user response:

The problem is regarding the files array and not the e.target HTMLInputElement, so, what you should actually be trying to do, is to assert if files is null or undefined before trying to access the first index.

You can do it like:

// the "?.[0]" will make it only try
// to access the index 0 if `files` is different from null or undefined
document.getElementById("form_file")!.onchange= function(e: Event) {
    let file = (e.target as HTMLInputElement).files?.[0];
}

Or this way:

document.getElementById("form_file")!.onchange= function(e: Event) {
    let file;

    if((e.target as HTMLInputElement).files){
        file = (e.target as HTMLInputElement).files
    }
}

CodePudding user response:

Free typed, unchecked and probably wrong, but to get rid of possibly null issues i would look to nest - it can't be null if your code only executes if i.e. file exists or e.target && e.target.files exists.

const file = document.getElementById("form_file");

if (file) {
  file.onChange = function(e: Event) {
    if (e.target && e.target.files) {
      let file = e.target.files;
    }
  }
}
  • Related