如何在不禁用 strictNullCheck 的情况下修复打字稿中的这个"object is possibly null"错误



这是我的打字脚本代码:

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];
}

我试过:

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

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

如何在不使用tsconfig中禁用strictNullChecks选项的情况下使其工作?

问候

问题是关于files数组,而不是e.targetHTMLInputElement,因此,您实际上应该尝试做的是,在尝试访问第一个索引之前断言文件是null还是undefined

你可以这样做:

// 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];
}

或者这样:

document.getElementById("form_file")!.onchange= function(e: Event) {
let file;
if((e.target as HTMLInputElement).files){
file = (e.target as HTMLInputElement).files
}
}

自由类型,未检查,可能是错误的,但为了消除可能的null问题,我希望嵌套-如果你的代码只在文件存在或e.target&amp;e.target.files存在。

const file = document.getElementById("form_file");
if (file) {
file.onChange = function(e: Event) {
if (e.target && e.target.files) {
let file = e.target.files;
}
}
}

相关内容

最新更新