title: Typescript convert unknown type to interface type
body: <p>I'd like to write a function <code>asA</code> that takes a parameter of type <code>unknown</code> and returns it as a specific interface type <code>A</code>, or throws an error if the parameter doesn't match the interface type <code>A</code>.</p>
  
  <p>The solution is supposed to be robust. I.e. if add a new field to my interface type <code>A</code>, the compiler should complain about my function missing a check for the new field until I fix it.</p>
  
  <p>Below is an example of such a function <code>asA</code>, but it doesn't work. The compiler says:</p>
  
  <blockquote>
    <p>Element implicitly has an 'any' type because expression of type '"a"'
    can't be used to index type '{}'. Property 'a' does not exist on type
    '{}'.(7053)</p>
  </blockquote>
  
  <pre><code>interface A {
      a: string
  }
  
  function asA(data:unknown): A {
      if (typeof data === 'object' &amp;&amp; data !== null) {
          if ('a' in data &amp;&amp; typeof data['a'] === 'string') {
              return data;
          }
      }
      throw new Error('data is not an A');
  
  }
  
  let data:unknown = JSON.parse('{"a": "yes"}');
  let a = asA(data);
  </code></pre>
  
  <p>How can I write a function <code>asA</code> as outlined above?</p>
  
  <p>I'm fine with using typecasts, e.g. <code>(data as any)['a']</code>, as long as there are no silent failures when new fields are added to <code>A</code>.</p>