enoshixi
enoshixi

Reputation: 309

TypeScript declaring namespaced external module?

I've got some legacy js modules that are either namespaced on window, or define'd if the page is using AMD. Example:

// foo/bar.js
(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(factory);
    } else {
        root.foo = root.foo || {};
        root.foo.bar = factory();
    }
} (this, function () {
    return {
        baz: function () {
            console.log("qux");
        }
    };
})); 

We're trying to start using TypeScript on future pages, but I'm having trouble creating definition files that will properly setup the external module. Ideally in TypeScript I'd like to be able to import bar = require("foo/bar");

After looking at how jquery.d.ts does it, I came up with:

    // foo/bar.d.ts
interface FooBar {
    baz: () => void;
}

declare module foo {
    export var bar: FooBar;
}    

declare module "foo/bar" {
    export = foo.bar; // Error: Could not find symbol 'bar'.
};

But I get the error on export = foo.bar. For now I'm just not declaring the external module and working around it using <amd-dependency />.

Upvotes: 0

Views: 2957

Answers (1)

Fenton
Fenton

Reputation: 251262

The exported item can be declared as a variable, with the appropriate type annotation. Here is an example (although I'm not sure exactly what you want to export)...

// foo/bar.d.ts
interface FooBar {
    baz: () => void;
}

declare module foo {
    export var bar: FooBar;
}    

declare module "foo/bar" {
    export = fb;
};

declare var fb: FooBar;

This results in a global variable fb and also supports the same "thing" being imported via "foo/bar".

If you aren't aiming to have an item in global scope, you can drop the variable inside the module, like this:

// foo/bar.d.ts
interface FooBar {
    baz: () => void;
}

declare module foo {
    export var bar: FooBar;
}    

declare module "foo/bar" {
    var fb: FooBar;

    export = fb;
}

Example calling code...

import foo = require("foo/bar");

var x = foo.baz();

Upvotes: 1

Related Questions