Use import/require in TypeScript to get interface declarations

dcstraw picture dcstraw · Oct 20, 2012 · Viewed 7.8k times · Source

If I reference a TypeScript declarations file (ex. jquery.d.ts) using the /// <reference path="..."/> syntax, it's up to me to make sure I load the corresponding library by some other means, i.e. just referencing the .d.ts file doesn't load the library.

Is there a way to make TypeScript generate a require() call for the library when I use it? If I wasn't using AMD/requirejs I could just call require manually, but I'd like to get this to work with AMD.

The advantage of this is that my dependencies wouldn't be defined in two places. Referencing the library from a .ts file would be enough to make sure it loads, rather than having to maintain the list of dependencies manually in my HTML.

Update: I opened a new question that clarifies my exact situation. I want to give credit for the answer to my original question since I didn't give all the necessary details.

Answer

Brian Terlson picture Brian Terlson · Oct 20, 2012

Yes, TypeScript supports "external" modules, which are basically first class AMD or CommonJS modules. For example:

MyLib.ts

export function foo() { return 'bar' }

MyProj.ts

import lib = module('./MyLib.ts')
lib.foo(); // returns bar

Compile this with "--module amd" and you'll get the proper module and require syntax generated for you.