title: Typescript - How to cast object to interface
body: <p>Suppose there is an interface</p>
  
  <pre><code>interface A {
    a: number;
  }
  </code></pre>
  
  <p>and currently I have a raw object</p>
  
  <pre><code>const a = { a: 1, b: '2' };
  </code></pre>
  
  <p>I expect a way to get <code>x</code> to be <code>{ a: 1 }</code>, which contains only members defined in interface.</p>
  
  <p>This can be achieved through creating an empty <code>{}</code> and looping over and filling in all <code>A</code>'s members, but considering interface members and object's redundant fields can be up to dozens, it is not practical to do so.</p>
  
  <p>I tried</p>
  
  <pre><code>let x = &lt;A&gt; a; // or let x = a as A;
  console.log((x as any).b); // still exist
  </code></pre>
  
  <p>I also looked up in <code>lodash</code> and found <code>keys</code> and <code>pick</code>, but these are targeted for class instance instead of interface.</p>