title: Typescript and React with File Upload (typing)
body: <p>I just started with TypeScript, so please bear in mind. I am trying to implement a simple file upload in React/TS. In general, I don't think I understand how to initialize objects, like in useState, and handle the possibilities properly. For example, consider this code where I am running a function when a user clicks an Upload button and I try to read the file from state and put in the formData to send it to my api endpoint):</p>
  <pre><code>
  const [fileSelected, setFileSelected] = React.useState&lt;File&gt;() // also tried &lt;string | Blob&gt;
  
  const handleImageChange = function (e: React.ChangeEvent&lt;HTMLInputElement&gt;) {
      const fileList = e.target.files;
  
      if (!fileList) return;
      
      setFileSelected(fileList[0]);
    };
  
     const uploadFile = function (e: React.MouseEvent&lt;HTMLSpanElement, MouseEvent&gt;) {
      const formData = new FormData();
      formData.append(&quot;image&quot;, fileSelected, fileSelected.name);
  
       // line above ^ gives me the error below
    };
  }
  </code></pre>
  <p><em>Argument of type 'string | Blob | undefined' is not
  assignable to parameter of type 'string | Blob'.
  Type 'undefined' is not assignable to type 'string |
  Blob'.ts(2345)</em></p>
  <p>How are you supposed to initialize your objects in useState? And if you don't initialize, like here, do you have to keep checking for null to keep the compiler happy? I just added a check in UploadFile to see if fileSelected is null. But then I had to do it again to reference fileSelected.name.</p>
  <p>So for objects, particularly something like this File type, how should you handle initializing it? But also, in general, how to handle object types?</p>
  <p>Not that it matters, but here's the markup part:</p>
  <pre><code>        &lt;Container className={classes.container}&gt;
            &lt;label htmlFor=&quot;photo&quot;&gt;
              &lt;input
                accept=&quot;image/*&quot;
                style={{ display: &quot;none&quot; }}
                id=&quot;photo&quot;
                name=&quot;photo&quot;
                type=&quot;file&quot;
                multiple={false}
                onChange={handleImageChange}
              /&gt;
  
              &lt;Button
                className={classes.buttons}
                component=&quot;span&quot;
                variant=&quot;contained&quot;
                onClick={uploadFile}
              &gt;
                Choose Picture
              &lt;/Button&gt;
            &lt;/label&gt;
          &lt;/Container&gt;
  </code></pre>