title: Getter function or default value for a typescript hashmap
body: <p>I am trying to write a simple getter for a value in an object with string keys or have some default of the same value type instead because I found myself needing to get values out of Maps many times. I assume this is a common pattern in Typescript. I am just looking for first level values no need to get nested data. It currently looks like this:</p>
  <pre><code>function getValueOrDefault&lt;T&gt;(
    object: Record&lt;string, T&gt;,
    path: keyof Record&lt;string, T&gt; &amp; string,
    orDefault: T
  ): T {
    if (path in object &amp;&amp; object[path] !== undefined) {
      return object[path] as T;
    } else {
      return orDefault;
    }
  }
  </code></pre>
  <p>It seems like TypeScript infers in the <code>object[path]</code> that T could still be <code>undefined </code> even if I am already checking <code>if object[path] !== undefined</code> in the if block. Why is this happening? I have to cast with <code>as T</code>. Smells like a bad thing to do. Also can you get a better way to achieve what I am looking for?</p>