title: Typescript: Constraint on a field of an union type
body: <p>I created a <strong>union type of objects</strong>. They all have a field <code>role</code> to differentiate them.
  Here we have <strong>teacher</strong> and <strong>student</strong>:</p>
  <pre class="lang-js prettyprint-override"><code>type User =
      {
          role: &quot;student&quot;;
          followClasses: string[];
      } |
      {
          role: &quot;teacher&quot;;
          since: number;
      };
  </code></pre>
  <p>Then I wanted to create a function to generate a <strong>default student</strong>:</p>
  <pre class="lang-js prettyprint-override"><code>const defaultStudent = (): User =&gt; ({
      role: &quot;student&quot;,
      followClasses: [],
  });
  </code></pre>
  <p>But since the <strong>return type</strong> is the union type <strong>User</strong>, typescript <strong>doesn't know that it's a student</strong>, and <strong>throw me a warning</strong> when I type this:</p>
  <pre class="lang-js prettyprint-override"><code>const student = defaultStudent();
  
  console.log(student.followClasses);
  //          Warning here ⮥
  </code></pre>
  <p>How to make the function <code>defaultStudent</code> have a constrained return type (student)?</p>