title: How to check if a strongly typed object contains a given key in TypeScript without it complaining?
body: <p>Take this code:</p>
  
  <pre><code>const lookup = {
      foo: 1,
      bar: 2
  }
  
  const getValueOrDefault = (name: string, defaultValue: number) =&gt; {
      if (name in lookup) {
          return lookup[name] // ERROR
      }
  
      return defaultValue
  }
  </code></pre>
  
  <p>The <code>lookup[name]</code> expression causes this TS error (<a href="http://www.typescriptlang.org/play/#code/MYewdgzgLgBANiEBrArgBxgXhgbwFAyEwBmiAXDAIwA0BRARgIYBOFATHgL556iSwBzAKZQAaozgohAeWYAxCRCFYYACjCMAtkIrRmASzACAlFgB8uOoX3E1G7TEPxEqNKfxFPMZiJTMwzsjoANr2QgC6VjDcUT5QfgHEikJceEA" rel="noreferrer">playground</a>):</p>
  
  <pre><code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: number; bar: number; }'.
    No index signature with a parameter of type 'string' was found on type '{ foo: number; bar: number; }'.
  </code></pre>
  
  <p>...even though I did <code>if (name in lookup)</code> to check it first. I tried <code>hasOwnProperty</code>, and that doesn't work either.</p>
  
  <p>TypeScript is often smart about refining types within conditional blocks, but not here. Why? And how can I make it work (without just hacking it by relaxing the type of <code>lookup</code>)?</p>