javascript - Vue.js + TS object is possibly 'null' on file input - Stack Overflow

I am trying to catch an event after file upload on file input.JS code:fileSelected(e: Event) {if ((&l

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 badges
Add a ment  | 

1 Answer 1

Reset to default 10

That 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信