Home > OS >  TypeScript : TS2531: Object is possibly 'null'
TypeScript : TS2531: Object is possibly 'null'

Time:02-25

       <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'.

CodePudding user response:

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 questino

// 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")
})
  • Related