I am trying to make a typescript + react fileinput component. However I'm getting typescript error 'Object is possibly null'. I have googled but couldn't find solution for this problem. How can I fix this problem without disabling typescript null check.
I'm getting errors on e.target.files[0]!
Here is the code below
import React from 'react';
    export default function ImageUpload() {
      const [selectedFile, setSelectedFile] = React.useState<File | string>('fileurl');
      const [imagePreviewUrl, setImagePreviewUrl] = React.useState<string | undefined | ArrayBuffer | null>();
      const fileChangedHandler = (e : React.ChangeEvent<HTMLInputElement>) => {
        setSelectedFile(e.target.files[0]!);
        const reader = new FileReader();
        reader.onloadend = () => {
          setImagePreviewUrl(reader.result);
        };
        reader.readAsDataURL(e.target.files[0]!);
      };
      const submit = () => {
        const fd = new FormData();
        fd.append('file', selectedFile);
      };
      let imagePreview = (<div className="previewText image-container">Please select an Image for Preview</div>);
      if (imagePreviewUrl) {
        imagePreview = (
          <div className="image-container">
            <img src={imagePreviewUrl} alt="icon" width="200" />
            {' '}
          </div>
        );
      }
      return (
        <div className="App">
          <input type="file" name="avatar" onChange={fileChangedHandler} />
          <button type="button" onClick={submit}> Upload </button>
          { imagePreview }
        </div>
      );
    }
                The "Object is possibly 'null'" error occurs when we try to access a property on an object that may have a value of null . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not null before accessing properties.
The exclamation mark is the non-null assertion operator in TypeScript. It removes null and undefined from a type without doing any explicit type checking.
HTMLInputElement has a built-in property files that is typeof FileList | null.
files: FileList | null;
Simply secure the possibility that files is null.
if (!e.target.files) return;
At the beginning of the function.
Guys this is the proper way of handling this issue:
            e.target.files instanceof FileList
              ? reader.readAsDataURL(e.target.files[0]) : 'handle exception'
Hope this helps. Cheers!
From the code, I suspect that e.target is nullable. You could modify e.target.files[0]! to e.target!.files[0]!, which will make error go away because you will essentially tell the Typescript compiler that "it will not be null, trust me". But instead, I would advise to handle the null case properly - check for null or undefined and do something appropriate, depending on your app logic.
if (!e.target.files || e.target.files.length === 0) {
      // you can display the error to the user
      console.error("Select a file");
      return;
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With