title: How can I assign a TypeScript type for event payloads for a class like EventEmitter?
body: <p>I have a class that is just like Node's EventEmitter (it could even be the same class).</p>
  
  <p>How do I type it in such a way that I can specify what the callback type is for each different event name?</p>
  
  <p>For example, I'd like for even <code>"foo"</code> to have a payload of type <code>number</code>, and event <code>"bar"</code> to have a payload of type <code>string</code>, as in:</p>
  
  <pre><code>const emitter = /* get emitter from somewhere. And how would the type definition look like? */
  
  emitter.on('foo', payload =&gt; {
    /* type of payload is number, enforced by TypeScript */
    testNumber('foo') // TS error, 'foo' is not a number
    testNumber(payload) // it works, payload is a number
  })
  
  emitter.on('bar', payload =&gt; {
    /* type of payload is string, enforced by TypeScript */
    testString(5) // TS error, 5 is not a string
    testString(payload) // it works, payload is a string
  })
  
  function testNumber( value: number ) {}
  function testString( value: string ) {}
  </code></pre>
  
  <p>How would we define the EventEmitter declaration so that it is possible to define events and their types, and to then let users use those events with the correct type checking?</p>
  
  <p>Maybe there's a way to define the type of EventEmitter such that when I create one I pass a type argument that contains all the expected types?</p>
  
  <p>Is there a way to do it dynamically after creation?</p>