Skip to content

Type inference considers only type amendments (if any are present), ignoring original typingsΒ #59576

@nicky1038

Description

@nicky1038

πŸ”Ž Search Terms

type inference amended types

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type inference

⏯ Playground Link

Link

πŸ’» Code

interface GenericEventTarget<TEventName extends string, TEvent extends Event> {
	addEventListener: (type: TEventName, listener: (event: TEvent) => void) => void

        // somehow, if addEventListener is declared this way, there is no error
        // addEventListener(type: TEventName, listener: (event: TEvent) => void): void
}

const addListener = <TEventName extends string, TEvent extends Event>(
	source: GenericEventTarget<TEventName, TEvent>,
    eventName: TEventName,
): void => {
	source.addEventListener(eventName, () => {})
}

// type amendment
interface Window {
	addEventListener(type: 'customEvent', listener: (this: Window, event: Event) => unknown, options?: {}): void
}

// works: it means that type amendment doesn't replace original typings
window.addEventListener('message', () => {})
// doesn't work: type inference only considers type amendment but not original typings
addListener(window, 'message')
// explicit specification of type parameters makes it work
addListener<'message', Event>(window, 'message')

πŸ™ Actual behavior

TS-2345 error in the line addListener(window, 'message'): Argument of type '"message"' is not assignable to parameter of type '"customEvent"'.
It is wrong because Typescript infers TEventName as customEvent, considering only type amendment and ignoring original typings.

πŸ™‚ Expected behavior

No errors are expected, because original typings for Window should also be considered

Additional information about the issue

I have a generic utility function that subscribes to certain event of provided event source, it looks like one in the example.

I use this utility function including for subscribing to events of window. After vite added its own type amendment for Window interface, errors in my code occurred, because in the case there are any type amendments, Typescript doesn't consider original typings for Window interface during type inference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions