microsoft / microsoft/TypeScript

Type information lost when passed as object key

Open
#42,076 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Needs Investigation
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 4.2.0-dev.20201222

Search Terms: type information lost

Code

js:

/** @typedef {{ [K in string] : (data: any) => void }} Event */

/**
 * @template {Event} E
 */
function createEventEmitter () {
  /** @type {Set<{ [T in keyof E]: E[T] }>} */
  const events = new Set()

  /**
   * @template {keyof E} T
   *
   * @param {T} event event register to
   * @param {E[T]} listener listener to register
   */
  function on (event, listener) {
    events.add({ [event]: listener })
  }

  return { on }
}

module.exports = { createEventEmitter }

ts:

type Event = { [K in string] : (data: any) => void }

export function createEventEmitter<E extends Event> () {
  const events: Set<{ [T in keyof E]: E[T] }> = new Set()

  function on<T extends keyof E> (event: T, listener: E[T]) {
    events.add({ [event]: listener })
  }

  return { on }
}

Expected behavior:
No errors

Actual behavior:
In function on variable event has type T extends keyof E, but add operation shows an error

изображение

Related Issues:
https://github.com/microsoft/TypeScript/issues/42060

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the TypeScript and JavaScript examples in the issue and inspect the error on events.add({ [event]: listener }). Trace the checker handling of generic computed object keys and mapped types. Done means both examples compile without errors and a regression test covers this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.