Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

addEventListener for message on Window or Worker #36606

Closed
mjgreen145 opened this issue Feb 4, 2020 · 2 comments
Closed

addEventListener for message on Window or Worker #36606

mjgreen145 opened this issue Feb 4, 2020 · 2 comments

Comments

@mjgreen145
Copy link

Search Terms: Window, Worker, addEventListener, union types

Code
I have a function which can either accept a Window or a Worker - there are many similarities between the two - and I want to be able to use common methods without caring about which of the two types the argument is. This function works if the argument w is set to be either Window or Worker in isolation, but not if it's the union type.

function myFunc(w: Worker | Window): void {
    const handler = (message: MessageEvent): any => {console.log(message)};
    w.addEventListener<"message">('message', handler);
}

Both Window.addEventListener and Worker.addEventListener have an overloaded type definition of:

addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;

Expected behavior:
No problems

Actual behavior:
<"message"> part throws an error - Typescript seems to only want to use the non-generic version of the addEventListener function, which my example doesn't fit since MessageEvent cannot be cast to Event.

Playground Link:
http://www.typescriptlang.org/play/#code/MYewdgzgLgBA7gRgFwwOoEswBMRxgXnkxzgG4AoUSWOAJhVRACcBrAUyYJjDb0dY4AKAOTCAlKRjlyAMwCuYYFHTgYAWwCeAMQXBBcBs3acAPmmK4xKAG4h0WGAG9yMVzCrQYACwCG2ADYcXIJqbBAQPgDmbCgAsmER0QCi1mxgUFYwfhoEAHxOHiCBAHT+IJEhCVFsYgC+FG7wxT5YWClpUAAy6NBpHAA8AESh4dWDuSIjiWzCADTefliBTBLktUA

@nmain100
Copy link

nmain100 commented Feb 4, 2020

Duplicate of #7294.

In fact, Window does not have the signature you're looking for, it has

addEventListener<K extends keyof WindowEventMap>(...)

This signature behaves equivalently to the worker scope one when K = "message", but that's not enough to merge the call signatures.

@mjgreen145
Copy link
Author

Ok, thanks. Will close this and follow linked thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants