Import external definitions

Barguast picture Barguast · Feb 8, 2015 · Viewed 11.6k times · Source

With Typescript, is there a way to import just the types from an external module?

Basically I just want one module to know the typings from another (to power Intellisense), but without the import being emitted in JavaScript. I want to do this because the module in question may or may not have been loaded - i.e. there isn't a hard dependency, but I want to have some typed code that runs and uses the module if it is there.

Hope this is clear.

Answer

Fenton picture Fenton · Feb 8, 2015

You can use a definition file along with a reference comment, which makes the types available without adding any import statements (such as require or define).

///<reference path="module.d.ts" />

You can automatically generate definition files during compilation, although for your purposes you'll probably want to hand-crank a custom one (depends on how you want to use it - the automatic one will expect to be imported).

Example Code

ModuleA.ts

class ExampleOne {
    doSomething() {
        return 5;
    }
}

export = ExampleOne;

ModuleB.ts

class ExampleTwo {
    doSomething() {
        return 'str';
    }
}

export = ExampleTwo;

Intended use:

import B = require('moduleb');

var a = new ExampleOne();
var b = new B();

To make this work, you would create your ModuleA.d.ts:

ModuleA.d.ts

declare class ExampleOne {
    doSomething(): number;
}

And then reference it like so:

/// <reference path="modulea.d.ts" />

import B = require('moduleb');

var a = new ExampleOne();
var b = new B();