title: Derive exact types from a typed object
body: <p>In TypeScript, I want to derive types from constants like this</p>
  <pre><code>const iso3ToCountry = {
    DEU: {
      name: &quot;Germany&quot;,
      continent: &quot;Europe&quot;,
      language: &quot;de&quot;,
    },
    GBR: {
      name: &quot;United Kingdom of Great Britain and Northern Ireland&quot;,
      continent: &quot;Europe&quot;,
      language: &quot;en&quot;,
    },
  } as const;
  
  type ISOCode = keyof typeof iso3ToCountry // same as &quot;DEU&quot; | &quot;GBR&quot;;
  </code></pre>
  <p>But, I also want to ensure that the values of the object implement the following interface:</p>
  <pre><code>interface CountryDetails {
    name: string;
    continent: string;
    language: string;
  }
  </code></pre>
  <p>The only way, that I have found to achieve both, is to use a helper function</p>
  <pre><code>function ensureType&lt;T extends Record&lt;string, CountryDetails&gt;&gt;(obj: T): T {
    return obj;
  }
  
  const iso3ToCountry = ensureType({
    DEU: {
      name: &quot;Germany&quot;,
      continent: &quot;Europe&quot;,
      language: &quot;de&quot;,
    },
    GBR: {
      name: &quot;United Kingdom&quot;,
      continent: &quot;Europe&quot;,
      language: &quot;en&quot;,
    },
  } as const);
  
  type ISOCode = keyof typeof iso3ToCountry;
  </code></pre>
  <p>Now <code>ISOCode</code> is equivalent to <code>&quot;DEU&quot; | &quot;GBR&quot;</code> and every value in the iso3ToCountry
  must have a <code>name</code>, <code>continent</code> and a <code>language</code>.</p>
  <p>The downside is that the <code>ensureType</code> function will be in the compiled JavaScript. We add code to our app, just to solve some compile-time problems.</p>
  <h2>Question:</h2>
  <p>Can I achieve type-checks in the &quot;iso3ToCountry&quot;-object <em>and</em> the ability to derive the key-type without having to add code that will remain in the compiled JavaScript.</p>