title: Angular - How to set default values for optional input properties
body: <p>I wonder what is the "Angular/Typescript way" to set up default values for optional properties in Angular component? I am having troubles when values passed to optional properties are <code>null</code> or <code>undefined</code>.</p>
  
  <p>Currently I am having something like this:</p>
  
  <pre><code>export class FooComponent implements OnInit {
    @Input() foo = 'foo';
    @Input() bar = 0;
    @Input() baz?: string;
  }
  </code></pre>
  
  <p>If you declare default value, you dont have to specify type since it is type of assigned value and property is optional by default. This is the case of <code>bar</code> and <code>foo</code> properties. </p>
  
  <p>Alternatively you can use <code>?</code> to mark that this property is optional but you cant declare its default value. This is the case of <code>baz</code> property.</p>
  
  <p>Now let us see what happens when you pass different values to those properties.</p>
  
  <pre><code>&lt;app-foo-component
    [foo]
    [bar]="null"
    [baz]="undefined"
  &gt;
  &lt;/app-foo-component&gt;
  </code></pre>
  
  <p>if I console log these properties, this is what I got:</p>
  
  <p><code>foo</code> will be correctly <code>'foo'</code></p>
  
  <p><code>bar</code> will be <code>null</code></p>
  
  <p><code>baz</code> will be <code>undefined</code></p>
  
  <p>Is there a elegant way to also set default values when passed values are null/undefined or do I need some checking in OnInit like this?</p>
  
  <pre><code>OnInit() {
    this.bar = this.bar || 0;
  }
  </code></pre>
  
  <p>It feels like there is some way to do this. To me, optional property means that value could be missing, null or unset but when I want to set default value, it only works when property is missing or empty. It still set value as null or undefined in these cases and that seems to be confusing.</p>