wikimedia-gadgets / types-mediawiki

TypeScript definitions for MediaWiki JS interface
GNU General Public License v3.0
23 stars 8 forks source link

Add a type variable to Hook #26

Closed Derugon closed 11 months ago

Derugon commented 1 year ago

Add a type variable to the Hook class, so that we can (optionally) specify the type of data shared when the hook is fired. E.g.:

/** @type {Hook<[string]>} */
var myHook = mw.hook('foo.bar');

myHook.add(function (myData) {
    myData.substring(1);   // ok
    myData.toPrecision(1); // not ok
});

Standard hook typing

We may specify the type variable on hooks used by default on MediaWiki. E.g. for wikitext.content:

    namespace mw {
        function hook(event: "wikitext.content"): Hook<[$content: JQuery]>;
        function hook(event: string): Hook;
    }

This is not backward-compatible, so this merge request does not propose to include any of these signatures.

siddharthvp commented 1 year ago

We may specify the type variable on hooks used by default on MediaWiki. E.g. for wikitext.content:

    namespace mw {
        function hook(event: "wikitext.content"): Hook<[$content: JQuery]>;
        function hook(event: string): Hook;
    }

This is not backward-compatible, so this merge request does not propose to include any of these signatures.

I think this is a great idea, and putting it like this makes it backward-compatible, I believe.

function hook<T = JQuery>(event: "wikipage.content"): Hook<T>;
function hook<T = any>(event: string): Hook<T>;

(once T is made non-array as suggested)

siddharthvp commented 11 months ago

Regarding 774c178eb6, I believe the type params on mw.hook are very much required, as otherwise we can't write something like mw.hook<JQuery[]>( 'wikipage.content' ); at all. The dtslint failure looks bogus, I'll just disable the rule. See also https://github.com/Microsoft/dtslint/issues/76.