-
Notifications
You must be signed in to change notification settings - Fork 24
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
Add generics to browser.runtime.sendMessage
#86
Comments
Interesting idea, but I'm not sure, how much work it would be to integrate that into the code generator. I'll check when I have some time. For the time being, I would advise to not use the |
The idea originally comes from me using this I think it would be great to provide this possibility because right now the Thanks a lot for your great tip! I will use it to improve my workaround for now 👍🏼 |
sendResponse: () => void but the correct signature would be sendResponse: <T>(data: T) => void More info: wxt-dev/wxt#299 |
I'll add the changes for sendMessage and sendNativeMessage. That part seems to be straight forward. However, onMessage is a different story. After all, it's not just about sendResponse, but also about the return-type and the message paramter as well. Currently, I have no neat typescript way to do this with the existing API due to the nature of the Events.Event type. Feel free to offer ideas. I can offer you a workaround for that though: // Add this somewhere in your code:
function typedEventListener<TMessage, TResponse>(listener: (
message: TMessage,
sender: MessageSender,
sendResponse: (message: TResponse) => void,
) => Promise<TResponse> | true | void) {
return listener as (
message: unknown,
sender: MessageSender,
sendResponse: (message: unknown) => void,
) => Promise<unknown> | true | void;
};
// Then wrap your listeners like this:
browser.onMessage.addListener(typedEventListener<{foo: string}, { bar: string }>((message, sender, sendResponse) => {
sendResponse({ bar: "true" });
return true;
}));
// Or promise-based:
x.onMessage.addListener(typedEventListener<{foo: string}, { bar: string }>((message, sender, sendResponse) => {
return Promise.resolve({ bar: "true" });
})); |
Cool! I really appreciate the effort and your suggested workaround! |
@Lusito Is there a reason why in the library, the type for the listener passed into
I was expecting it to allow returning Upon further investigation, this looks like a regression so I filed a new issue for it here: #109 |
Hey,
I would love to use
browser.runtime.sendMessage
the following way so that I can specify the type of the message that I am sending.My current workaround is this but generics would be much nicer
Also for
browser.runtime.onMessage.addListener
it would be useful to be able to specify the type of the callback argument.Would it be possible to add this?
Thanks a lot!
The text was updated successfully, but these errors were encountered: