Skip to content Skip to sidebar Skip to footer

How Should I Define A Global Typescript Variable In A Definition File So That It Can Be Imported?

I have an external JS library with a global parameter: function Thing() { ... } ... var thing = new Thing(); There is a TypeScript definition file, so in thing.d.ts: declare var

Solution 1:

If the only way to use that library is by accessing its globals (as opposed to importing it as node module or amd or umd module), then the easiest way to go is have a declaration file without any exports at top level. Just declaring a variable is enough. To use it, you have to include that declaration file when compiling your typescript code, either by adding it to files or include in tsconfig.json, or directly on command line. You also have to include the library with a <script> tag at runtime.

Example: thing.d.ts

declarevar thing: ThingStatic;

declareinterfaceThingStatic{
    functionOnThing(): ThingFoo;
}

declareinterfaceThingFoo{
}

test-thing.ts

const x:ThingFoo = thing.functionOnThing();

can be compiled together

./node_modules/.bin/tsc test-thing.ts thing.d.ts

the result in test-thing.js:

var x = thing.functionOnThing();

See also this question about ambient declarations.

Note: there are module loaders out there that allow using global libraries as if they were modules, so it's possible to use import statement instead of <script> tag, but how to configure these module loaders to do that is another, more complicated question.

Post a Comment for "How Should I Define A Global Typescript Variable In A Definition File So That It Can Be Imported?"