definitelytyped-firefox-webext-browser icon indicating copy to clipboard operation
definitelytyped-firefox-webext-browser copied to clipboard

Callback type - how to use in a separate function?

Open lukaszpolowczyk opened this issue 3 years ago • 1 comments

I have this code, and it has types for callback:

obraz

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

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) {
}

lukaszpolowczyk avatar Dec 15 '21 19:12 lukaszpolowczyk

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 avatar Jan 02 '22 22:01 jsmnbom

@jsmnbom I use JSDoc. It works uses TypeScript, but relies on comments.

lukaszpolowczyk avatar Jan 11 '23 22:01 lukaszpolowczyk