title: React: make typescript infer children type based on conditions in another component
body: <p>I want to write a component that render its children only if some given prop is not null (e.g. to render a loader while fetching some data and update with the actual data when fetch completes).
  This is pretty simple:</p>
  
  <pre><code>import React, { ReactElement, ReactNode, useState } from 'react'
  
  type TState = {
      data: {
          text: string
      } | null
  }
  
  type NotNullProps = {
      children: ReactNode
      state: TState
  }
  
  const NotNull = ({ children, state }: NotNullProps) =&gt; {
      if (!state.data) {
        return null
      }
  
      return &lt;&gt;{children}&lt;/&gt;
  }
  </code></pre>
  
  <p>Now, what if I want to use this component <strong>this way</strong>?</p>
  
  <pre><code>const Example = () =&gt; {
      const [state] = useState&lt;TState&gt;({ data: null })
  
      return (
          &lt;NotNull state={state}&gt;
              &lt;div&gt;{state.data.text}&lt;/div&gt; // &lt;--- "Object is possibly 'null'."
          &lt;/NotNull&gt;
      )
  }
  </code></pre>
  
  <p>Typescript correctly signals that <code>state.data</code> can be null because it can't infer what is happening in <code>NotNull</code>, but <code>state.data</code> will never be null since <code>NotNull</code> checks for it.<br>
  I know this can be solved with render props but they add a bit of clutter to the code. So, is there a way to type <code>NotNull</code> in such a way that typescript does not complains/can infer what is happening?</p>
  
  <p>Here's a playground to try it: <a href="https://tsplay.dev/zwORWq" rel="nofollow noreferrer">https://tsplay.dev/zwORWq</a></p>
  
  <p>(Yes, I know about <code>Suspense</code> and other stuff but it is not relevant to this question. I just want to know if there's a way to type this component in a way that typescript can infer that the value is not null (again, without render props)).</p>