Typescript How to export two classes (in separate files) into one module?

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 combine them into one module. How can I understand that?

 ///<reference path='a.ts' /> ///<reference path='b.ts' /> module Common { export class A extends AClass {} export class B extends BClass {} } 

is talking:

Cannot find the name "AClass".

and

Unable to find the name "BClass".

I can import classes

 import AClass = require('a'); import BClass = require('b'); module Common { } 

But how can I export them correctly?

Unable to find information in documentation. Please tell me the best way to implement declarations in one module? Thank you in advance

+5
source share
3 answers

If you declare a class, as you showed, you include it in the "global" namespace. To declare a class inside a module, simply wrap it in a module declaration:

 module Common{ export class ClassA{} } 

you can update the module in several files, only one javascript object will be created for the module.

+6
source

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'; 
+5
source

You have export in front of your class declarations:

 export class AClass { 

This turns the 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, because this is what I imported its containing module as.

Alternatively, you can rename module a after it contains one class, for example

AClass.ts

 class AClass { public constructor () { console.log('AClass'); } } export = AClass; 

Under the "assignment" of export we make this class the only output of the module. Therefore, in another module:

 import AClass = require("AClass"); var a = new AClass(); // no prefix needed 

This may be more accurate if your module exports only one class (or function).

+4
source

Source: https://habr.com/ru/post/1215755/


All Articles