title: In Typescript, how to select a type from a union, using a literal type property of said type?
body: <p>I have a reducer in react. The action can be one of 8 types, but for simplicity, let's imagine that there's only 2 types</p>
  <pre class="lang-js prettyprint-override"><code>type Add = {
    type: 'add';
    id: string;
    value: string;
  }
  
  type Remove = {
    type: 'remove';
    id: string;
  }
  
  type Action = Add | Remove;
  </code></pre>
  <p>Instead of using a switch case, I'm using an object of handlers, where each handler is a function that handles a specific action</p>
  <pre class="lang-js prettyprint-override"><code>const handlers = {
    add: (state, action) =&gt; state,
    remove: (state, action) =&gt; state,
    default: (state, action) =&gt; state,
  }
  
  const reducer = (state, action) =&gt; {
    const handler = handlers[action.type] || handlers.default;
    return handler(state, action);
  }
  </code></pre>
  <p>Now I want to type the <code>handlers</code> object appropriately. So the handler function should accept an action of type corresponding to its key in the <code>handlers</code> object.</p>
  <pre class="lang-js prettyprint-override"><code>type Handlers = {
    [key in Action[&quot;type&quot;]]: (state: State, action: Action) =&gt; State
  //                                                ↑this here should be the action which has type
  //                                                matching to it's key. So when the key is
  //                                                'add', it should be of type Add, and so on.
  }
  </code></pre>
  <p>All I could think of is to explicitly state the key and the matching action type. Is There a way to 'pick' the type from the union, according to the value of the key?</p>