How do I import other TypeScript files?
When using the TypeScript plugin for vs.net, how do I make one TypeScript file import modules declared in other TypeScript files?
file 1:
module moo
{
export class foo .....
}
file 2:
//what goes here?
class bar extends moo.foo
{
}
Solution 1:
From TypeScript version 1.8 you can use simple import
statements just like in ES6:
import { ZipCodeValidator } from "./ZipCodeValidator";
let myValidator = new ZipCodeValidator();
https://www.typescriptlang.org/docs/handbook/modules.html
Old answer: From TypeScript version 1.5 you can use tsconfig.json
: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html
It completely eliminates the need of the comment style referencing.
Older answer:
You need to reference the file on the top of the current file.
You can do this like this:
/// <reference path="../typings/jquery.d.ts"/>
/// <reference path="components/someclass.ts"/>
class Foo { }
etc.
These paths are relative to the current file.
Your example:
/// <reference path="moo.ts"/>
class bar extends moo.foo
{
}
Solution 2:
Typescript distinguishes two different kinds of modules: Internal modules are used to structure your code internally. At compile-time, you have to bring internal modules into scope using reference paths:
/// <reference path='moo.ts'/>
class bar extends moo.foo {
}
On the other hand, external modules are used to refernence external source files that are to be loaded at runtime using CommonJS or AMD. In your case, to use external module loading you have to do the following:
moo.ts
export class foo {
test: number;
}
app.ts
import moo = module('moo');
class bar extends moo.foo {
test2: number;
}
Note the different way of brining the code into scope. With external modules, you have to use module
with the name of the source file that contains the module definition. If you want to use AMD modules, you have to call the compiler as follows:
tsc --module amd app.ts
This then gets compiled to
var __extends = this.__extends || function (d, b) {
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
}
define(["require", "exports", 'moo'], function(require, exports, __moo__) {
var moo = __moo__;
var bar = (function (_super) {
__extends(bar, _super);
function bar() {
_super.apply(this, arguments);
}
return bar;
})(moo.foo);
})