title: React context and nullable values in state
body: <p>I'm trying to make a context in react that will hold some values as defined by an interface (<code>Client</code> in the example below). My problem is that it requires me to make that field nullable in the state interface (<code>ClientState</code>), meaning I would have to check for null values everywhere I consume the context. I want to avoid that.</p>
  <p>Example code:</p>
  <pre class="lang-js prettyprint-override"><code>interface Client {
    value1: string,
    value2: number
  }
  
  interface ClientState {
      client?: Client
  }
  
  const initialState: ClientState = {
      client: undefined
  }
  
  const ClientContext = React.createContext&lt;ClientState&gt;(initialState);
  
  export const useClient = (): ClientState =&gt; useContext(ClientContext);
  
  export const EmployeeContextProvider = ({ children }: PropsWithChildren&lt;{}&gt;) =&gt; {
      const [state, setState] = useState({});
  
      // abstracted, not relevant to this problem
      const loadFiles = () =&gt; {
          setState(
              {
                  value1: &quot;test&quot;,
                  value2: 1
              }
          )
      }
  
      useEffect(() =&gt; loadFiles(), []);
  
      return (
          &lt;ClientContext.Provider value={state}&gt;
                  {children}
          &lt;/ClientContext.Provider&gt;
      )
  }
  </code></pre>
  <p>So far I've tried and deemed unsatisfactory:</p>
  <ol>
  <li>Giving the <code>client</code> field in <code>initialState</code> a dummy object. The problem with this is that the real version of this has a large number of these fields, meaning lots of dummy code.</li>
  <li>Adding a check to <code>useClient()</code> for members of the <code>Client</code> interface, same problem as 1.</li>
  </ol>
  <p>Also of semi-relevance is that I don't need to modify this context beyond initialization and it's perfectly fine for it to be read-only.</p>