title: TypeScript: Type 'string | undefined' is not assignable to type 'string'
body: <pre><code>interface SomeType {
    a: string;
    b?: string;
  }
  
  const foo: SomeType = {
    a: 'hello',
    b: 'there'
  };
  
  const bar: SomeType = {
    a: 'hello'
  };
  bar.b = 'there';
  
  // Error on this line
  const str: string = foo.b;
  
  // These lines have no error
  const str2: string = foo.b ? foo.b : '';
  const str3: string = foo.b!;
  const str4: string = bar.b;
  </code></pre>
  
  <p>In the example above, we have 2 flavors creating an object of <code>SomeType</code>, which has an optional property <code>b</code>. When declaring <code>foo</code>, we are setting the value of <code>b</code> when the object is created. For <code>bar</code>, we are setting a value of <code>b</code> after the object has been created.</p>
  
  <p>When creating the first string, <code>str</code>, there is an error:</p>
  
  <blockquote>
    <p><strong>Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.ts(2322)</strong></p>
  </blockquote>
  
  <p>This error is mitigated with the approaches for <code>str2</code> and <code>str3</code>. I understand that in these examples, we are either checking the value of <code>foo.b</code> or asserting that we know <code>foo.b</code> has a value.</p>
  
  <p>I'm not understanding why the error does not appear when <code>str4</code> is created. Why is TypeScript able to detect that <code>bar.b</code> is <strong>not</strong> <code>undefined</code> but it wasn't able to detect the same thing for <code>foo.b</code>? What is it about the way we are setting the property that results in this error?</p>
  
  <p>(TypeScript Version 3.8.2)</p>