title: Ref object is possibly undefined TypeScript React
body: <p>I have a component that uses a hook to set the input value into component state. I want to add a class when the input value is more than 0 characters in length, however I'm coming across an issue where TypeScript says my ref may be undefined.</p>
  
  <p>I can't get rid of this error even if I check if the ref exists in the conditional that wraps the code to add the class. I'm not sure on the solution to this.</p>
  
  <p><strong>Error:</strong> <code>Object is possibly 'undefined'</code> on       <code>inputValue.current.classList.add(inputHasContentClassName);</code></p>
  
  <pre><code>import React, { useState, useEffect, useRef } from 'react';
  
  const Component: React.FC = () =&gt; {
    const [inputValue, setInputValue] = useState('');
    const myRef = useRef();
  
    useEffect(() =&gt; {
      const inputHasContentClassName = 'input--has-value';
  
      if (inputValue.length &gt; 0 &amp;&amp; inputValue) {
        inputValue.current.classList.add(inputHasContentClassName);
      } else {
        inputValue.current.classList.remove(inputHasContentClassName);
      }
    }, [inputValue]);
  
    function handleInputChange(e: React.FormEvent&lt;HTMLInputElement&gt;) {
      setInputValue(e.currentTarget.value);
    }
  
    function handleSubmit(e: React.FormEvent) {
      e.preventDefault();
  
      console.log('Submit form');
    }
  
    return (
      &lt;&gt;
        &lt;section&gt;
          &lt;form onSubmit={handleSubmit}&gt;
            &lt;div&gt;
              &lt;input
                ref={myRef}
                onChange={handleInputChange}
                type="number"
              /&gt;
              &lt;label&gt;Input Label&lt;/label&gt;
            &lt;/div&gt;
            &lt;button
              type="submit"
              disabled={inputValue.length === 0}
            &gt;
              Submit
            &lt;/button&gt;
          &lt;/form&gt;
        &lt;/section&gt;
      &lt;/&gt;
    );
  };
  
  export default Component;
  </code></pre>