title: Function for getting type of TypedDict value that works with static type checker
body: <p>I am looking to make a Python (3.8+) function that is:</p>
  <ul>
  <li>Input: key of a <code>TypedDict</code></li>
  <li>Output:
  <ul>
  <li>Returns the value (easy)</li>
  <li>Is appropriately type hinted (where I am stuck)</li>
  </ul>
  </li>
  </ul>
  <p>Here is a code sample to help explain:</p>
  <pre class="lang-py prettyprint-override"><code>from typing import Any, Literal, TypedDict
  
  class Foo(TypedDict):
      bar: int
      baz: str
      spam: Any
  
  foo = Foo(bar=0, baz=&quot;hi&quot;, spam=1.0)
  
  def get_type(key: Literal[&quot;bar&quot;, &quot;baz&quot;]):  # How to type hint the return here?
      &quot;&quot;&quot;Function that get TypedDict's value when passed a key.&quot;&quot;&quot;
      val = foo[key]
      # This works via intelligent indexing
      # SEE: https://mypy.readthedocs.io/en/stable/literal_types.html#intelligent-indexing
      reveal_type(val)  # mypy: Revealed type is 'Union[builtins.int, builtins.str]'
      return val
  
  fetched_type = get_type(&quot;bar&quot;)
  reveal_type(fetched_type)  # mypy: Revealed type is 'Any'
  # I would like this to have output: 'int'
  </code></pre>
  <p>In case you can't tell, the static type checker I am using is <code>mypy</code>.</p>
  <p>The function I have above <code>get_type</code> gets halfway there with <a href="https://mypy.readthedocs.io/en/stable/literal_types.html#intelligent-indexing" rel="nofollow noreferrer">intelligent indexing</a>, but I am not sure how to type hint the return of <code>get_type</code>.</p>
  <p>What type hint should I put for the return of <code>get_type</code>?</p>
  <hr />
  <p><strong>Research</strong></p>
  <p>Both of these questions</p>
  <ul>
  <li><a href="https://stackoverflow.com/questions/52747473/factory-function-for-mypy-typeddict">Factory function for mypy `TypedDict`</a></li>
  <li><a href="https://stackoverflow.com/questions/62354233/how-to-statically-get-typevar-parameters-from-a-generic-for-use-in-static-type-c">How to statically get TypeVar parameters from a Generic for use in static type checking?</a></li>
  </ul>
  <p>provide answers using <code>TypeVar</code>.  Is there some way of using <code>TypeVar</code> with <code>TypedDict</code>?</p>