Skip to content

keyof ignores constraint #44985

@alesmenzel

Description

@alesmenzel

Bug Report

🔎 Search Terms

keyof, generic constraint

🕗 Version & Regression Information

  • This is a crash ❌ No
  • This changed between versions _______ and _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about keyof
  • I was unable to test this on prior versions because it seems to be consistent behavior in all tested versions

⏯ Playground Link

Playground link with relevant code

💻 Code

// Implementation of event emitter - sample without all methods
type Listener<Event> = (event: Event) => void;

// Here the "key: K" complains "An index signature parameter type must be either 'string' or 'number'"
type Listeners<Events, K extends string & keyof Events> = {[key: K]: Listener<Events[K]>[]}

class EventEmitter<Events extends {[key: string]: unknown}> {
  #listeners: Listeners<Events, keyof Events>

  constructor() {
    this.#listeners = {}
  }
}

// Usage
type MyEvents = {
    connect: void
    reconnect: number
    error: Error
    disconnect: void
}
const emitter = new EventEmitter<MyEvents>()

🙁 Actual behavior

I am getting ts errors even though the types work as expected. See // usage section

🙂 Expected behavior

The keyof returns the same type as the constraint generic and thus will be valid as index signature.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions