definitelytyped-firefox-webext-browser
definitelytyped-firefox-webext-browser copied to clipboard
Callback type - how to use in a separate function?
I have this code, and it has types for callback:

But when I want to keep the callback as a separate function, I don't know how to set the types for it:

How to set types for this function? I tried for example like this:
/** @type {browser.runtime.onMessage} */
...but it doesn't work.
I know this question is more about TypeScript/JSDoc, but it's also a question of how the type file is prepared. Maybe it needs to be generated differently?
For example, for the idb library, it is added like this:
/** @type {idb.OpenDBCallbacks["upgrade"]} */
function upgradeCb (db, oldVersion, newVersion, transaction) {
}
Uhh, I have no clue, sorry :/
I've only used this types with typescript and the /** @type {} */ stuff that you're doing doesn't seem to be typescript at all.
But if you are in fact using typescript then you can either put the function directly in the call and typescript will infer it.
browser.runtime.onMessage.addListener((message: MyMessageType, sender, sendResponse) => {
...
});
Or if that's not an option then you can either look in the type file and find out that sender should be browser.runtime.MessageSender.
Or alternatively infer it from the event using something like this:
type EventCallbackType<T> = T extends WebExtEvent<infer T> ? T : never
const handleMessage: EventCallbackType<typeof browser.runtime.onMessage> = (message, sender, sendResponse) => {
...
};
browser.runtime.onMessage.addListener(handleMessage)
@jsmnbom I use JSDoc. It works uses TypeScript, but relies on comments.