Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define global namespace/variable within a TypeScript module

In TypeScript I can define a global/top-level namespace and use it in another file like so:

namespace foo.blah {
    export function baz() {
        console.log('hello');
    }
}

And in another file, this works:

foo.blah.baz();

However, if I then import something from another module:

import Thing from 'boo';

namespace foo.blah {
    export function baz() {
        console.log('hello');
    }
}

Suddenly my whole file is a module, the foo.blah namespace is local, not global, and the foo.blah.baz() call in the other file fails. export namespace ... just causes the namespace to become part of the module's export, not a global.

Is there a way to write a TypeScript file which imports from other modules but also defines global/top-level symbols?

At the moment I'm doing this:

import Thing from 'boo';
import * as $ from 'jquery';

namespace foo.blah {
    export function baz() {
        console.log('hello');
    }
}

$.extend(true, window, {foo});

Which works, but the TypeScript compiler still can't see that foo.blah... exists as a global in other files.

(The file is the entry point for Webpack, and I'm trying to import things from other modules in the Webpack bundle and assign them to globals so they can be used in <script> tags on the page.)

like image 855
Jesse Avatar asked Nov 23 '15 07:11

Jesse


People also ask

How do you declare a variable global in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.

How do you define a namespace in TypeScript?

Namespace Declaration We can create a namespace by using the namespace keyword followed by the namespace_name. All the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword. The export keyword makes each component accessible to outside the namespaces.

How do I refer a namespace in a file student ts?

To use it, it must be included using triple slash reference syntax e.g. ///<reference path="path to namespace file" /> . Must import it first in order to use it elsewhere. Compile using the --outFile command. Compile using the --module command.


1 Answers

When you add the import, you switch from internal modules to external ones, as the spec says:

In external modules, relationships between files are specified in terms of imports and exports at the file level. In TypeScript, any file containing a top-level import or export is considered an external module.

http://www.typescriptlang.org/Handbook#modules-going-external

The philosophy behind external modules is to avoid global objects, why don't you create a new module with foo.blah (and all the stuff you need) and import it as TypeScript expects it?

like image 140
Martin Vseticka Avatar answered Sep 19 '22 15:09

Martin Vseticka