Reputation: 2318
I have two classes declared in two separate files.
a.ts
export class AClass {
public constructor () {
console.log('AClass');
}
}
b.ts
export class BClass {
public constructor () {
console.log('BClass');
}
}
I want to merge them in one module. How I can realise it?
///<reference path='a.ts' />
///<reference path='b.ts' />
module Common {
export class A extends AClass {}
export class B extends BClass {}
}
says:
Cannot find name 'AClass'.
and
Cannot find name 'BClass'.
I can import classes
import AClass = require('a');
import BClass = require('b');
module Common {
}
But how I can correctly export them?
Cannot find any information in documentation. Please, tell me the best way to realise declarations in one module? Thank you in advance
Upvotes: 10
Views: 23659
Reputation: 4877
I do it like this:
m/a.ts
export class A {
}
m/b.ts
export class B {
}
m/index.ts
export { A } from './a.ts';
export { B } from './b.ts';
And then I do: consumer.ts
import { A, B } from './m';
Upvotes: 25
Reputation: 116674
You have export
in front of your class declarations:
export class AClass {
This turns that source file into an external module. This means that you will need to use import
/require
from another module:
import a = require("a");
module Common {
export class A extends a.AClass {}
}
Note that AClass
appears to be a member of a
because that's what I imported its containing module as.
Alternatively you could rename a
module after a single class that it contains, e.g.
AClass.ts
class AClass {
public constructor () {
console.log('AClass');
}
}
export = AClass;
By "assigning" to export
we make that class be the entire single output of module. Hence in another module:
import AClass = require("AClass");
var a = new AClass(); // no prefix needed
This can be tidier if your module only exports a single class (or function).
Upvotes: 5
Reputation: 12619
If you declare class like you showed you include it in the 'global' namespace. To declare class inside a module just wrap it in module declaration:
module Common{
export class ClassA{}
}
you can redeclare module in multiple files only one javascript object will be created for the module.
Upvotes: 6