-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Description
π 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
π» 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.