最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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];
}
发布评论

评论列表(0)

  1. 暂无评论