The50
The50

Reputation: 1178

Vue.js + TS object is possibly 'null' on file input

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?

Upvotes: 2

Views: 1824

Answers (1)

Terry
Terry

Reputation: 66188

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

Upvotes: 10

Related Questions