Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript : TS2531: Object is possibly 'null'

Tags:

typescript

       <div >
            <input type="file"  id="uploadImage"/>
            <button
                @click="Upload"
                style="width: 80px;height: 30px;"
            >
                upload
            </button>
          </div>

  //upload()
    const upload = () => {
      const file= (document.getElementById('uploadImage') as HTMLInputElement).files[0];

    }

I want to get the value of < input type=file/ >, but there is the following error. How to write it will solve it? TS2531: Object is possibly 'null'.

like image 319
鹰 9am Avatar asked Oct 23 '25 15:10

鹰 9am


1 Answers

TypeScript is saying you must handle the case where document.getElementById('uploadImage') could return null and where .files could return null.

The first is not possible in your case because you are in a handler for #uploadImage so you can just add a dummy null check or even a non-null assertion, that is, input!.files[0].

const input = document.getElementById('uploadImage') as HTMLInputElement; 
// file may be null if use canceled out of the dialog
const file = input!.files?[0]

Another option would be to get the element from the event, but .files could still be null.

 const upload = (e: ) => {
      const file= (e.target as HTMLInputElement).files?.[0];
 }

Lastly, you should be checking for the change event, not the click since the user hasn't selected anything when they click.

You can see a working example with plain TS here I don't know what framework you're using but it's not really relevant to your question.

// Non-null assertion because we know input exists.
const input: HTMLInputElement = document.querySelector("input")!;

input.addEventListener("change", function test(e: Event) {
  const file = input.files?.[0];
  // .files may be null, handle it properly
  console.log(file ? "File selected: " + file.name : "No file selected")
})
like image 64
Juan Mendes Avatar answered Oct 25 '25 08:10

Juan Mendes