title: Type safe field assignment
body: <p>I want to assign a number to an object's field based on some condition like this:</p>
  <pre class="lang-js prettyprint-override"><code>function maybeANumber(): number | undefined {
    const n = Math.random();
    return n &gt; 0.5 ? n : undefined;
  }
  
  function maybeSetNumber(target: any, field: any) {
    const num = maybeANumber();
    if (num !== undefined) {
      target[field] = num;
    }
  }
  </code></pre>
  <p>This works because I used <code>any</code> liberally, but how can I type this correctly, so that it detects type errors:</p>
  <pre class="lang-js prettyprint-override"><code>
  interface Foo {
    a: string,
    b: number,
  }
  
  const foo: Foo = { a: &quot;&quot;, b: 0 };
  
  maybeSetNumber(foo, &quot;a&quot;); // Should be a compile-time error.
  maybeSetNumber(foo, &quot;b&quot;); // Should be a ok.
  </code></pre>
  <p>Is there any way to do this?</p>
  <p><em>Edit:</em> Important clarification: the field names are static. I don't need it to work with arbitrary strings. I've tried a load of stuff with <code>keyof</code> but couldn't quite figure it out.</p>