David Harkness
David Harkness

Reputation: 36562

Copy module function declarations to global namespace

I have declared forty or so functions inside a module, but there is also a method that copies each function to the global namespace (or any target object provided).

module JsHamcrest {
    declare function assertThat(actual: any, matcher: Matcher): void;

    // lots and lots of Matcher factory methods
    declare function bool(): Matcher;
    declare function func(): Matcher;
    declare function number(): Matcher;
    declare function object(): Matcher;
    declare function string(): Matcher;
    ...

    declare function copyMembers(target: any): void;
}

This allows developers to use the namespaced functions in JavaScript as-is via the module name

JsHamcrest.assertThat(5, JsHamcrest.number());

or copy them into the global namespace to improve readability.

JsHamcrest.copyMembers(window);

assertThat('foo', string());

The shortest solution I've come up with so far is to assign each function to a global variable:

var number = JsHamcrest.number;

But at least in PhpStorm the JSDoc isn't applied to the copies, and it's still prone to error (though less so).

tl;dr How can I declare these top-level definitions without copy-pasting them and still have IDEs auto-complete with documentation?

Upvotes: 1

Views: 439

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221342

There isn't a way to "bulk" copy members into the global namespace (thankfully?), but you can use import instead of var and should get JSDoc information assuming your editor uses the TypeScript Language service:

enter image description here

Upvotes: 2

Related Questions