I am trying to catch an event after file upload on file input.
JS code:
fileSelected(e: Event) {
if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) {
this.file = (<HTMLInputElement>e.target).files[0];
}
}
And my file variable is defined as null. I want to select the first element of files, but I get the error:
Object is possibly null
I found a solution that you first have to check if it's not empty, but I get the same error on if statement itself. Any ideas?
I am trying to catch an event after file upload on file input.
JS code:
fileSelected(e: Event) {
if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) {
this.file = (<HTMLInputElement>e.target).files[0];
}
}
And my file variable is defined as null. I want to select the first element of files, but I get the error:
Object is possibly null
I found a solution that you first have to check if it's not empty, but I get the same error on if statement itself. Any ideas?
Share Improve this question edited Jul 7, 2020 at 10:27 The50 asked Jul 7, 2020 at 10:20 The50The50 1,1884 gold badges25 silver badges57 bronze badges1 Answer
Reset to default 10That is because TypeScript cannot perform type narrowing in the code you've shared. If you (1) assign them to variables and (2) add guard clauses to your logic to enforce non-null value checks, that should fix the issue:
fileSelected(e: Event) {
const target = e.target as HTMLInputElement;
const files = target.files;
// Guard clause to catch cases where `files` or `files[0]` is falsy (null included)
if (!files || !files[0])
return;
// At this point, both `files` and `files[0]` will be non-null
// And `files` will have an inferred type of `FilesList` instead of `FilesList | null`
this.file = files[0];
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744971555a4603996.html
评论列表(0条)