Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript Object is possibly null when getting files from event

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>
      );
    }
like image 569
Jonghyeon Lee Avatar asked May 03 '20 11:05

Jonghyeon Lee


People also ask

How do I fix TypeScript object is possibly null?

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.

How do I tell TypeScript to ignore undefined?

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.


4 Answers

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.

like image 53
kind user Avatar answered Oct 22 '22 12:10

kind user


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!

like image 21
Viktor Dojcinovski Avatar answered Oct 22 '22 10:10

Viktor Dojcinovski


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.

like image 30
Max Yankov Avatar answered Oct 22 '22 12:10

Max Yankov


if (!e.target.files || e.target.files.length === 0) {
      // you can display the error to the user
      console.error("Select a file");
      return;
    }
like image 1
Yilmaz Avatar answered Oct 22 '22 10:10

Yilmaz