2

I have a class in a module.

module Foo {
    export class Bar {

    } 

    /* Some more interfaces and classes to be used only in this module */
}
var bar = new Foo.Bar();

This class is for a library, and I don't want other users to write Foo.Bar but just Bar to use my Bar class:

var bar = new Bar();

I can do this by defining a new variable Bar.

var Bar = Foo.Bar;

var bar = new Bar();

However, now I have a problem. I cannot use the Bar as a TypeScript type identifier.

function something(bar: Bar) { // Compiler: Could not find symbol 'Bar'.

}

I can also solve this problem by defining a new class that extends Foo.Bar.

class Bar extends Foo.Bar {

}

var bar = new Bar();
function something(bar: Bar) {

}

However, the resulting Bar class is not exactly same with Foo.Bar, as Bar === Foo.Bar and Bar.prototype === Foo.Bar.prototype both returns false.

I tried to find a method using TypeScript module feature such as import and require, but it seems I cannot do this with them. Is there any good method to expose my Bar class to global?

3 Answers 3

2

Instead of

interface Bar extends Foo.Bar {
}
var Bar = Foo.Bar;

You can simply do :

import Bar = Foo.Bar;

Complete Example :

module Foo {
    export class Bar {
        x: number
    } 

    /* Some more interfaces and classes to be used only in this module */
}

import Bar = Foo.Bar;

var bar = new Bar();
function something(bar: Bar) {

}
Sign up to request clarification or add additional context in comments.

3 Comments

Much simpler! This is what I want. Thank you very much!
Oops. Resulting d.ts file now does not includes Bar as global class object. Hmm...
The d.ts problem seems to be fixed in the new compiler. See: github.com/Microsoft/TypeScript/issues/346 Anyone who uses current version 1.1 compiler should add import Bar = Foo.Bar; line in d.ts file by themselves.
0

It turns out that this works as intended.

module Foo {
    export class Bar {
        x: number
    } 

    /* Some more interfaces and classes to be used only in this module */
}
interface Bar extends Foo.Bar {
}
var Bar = Foo.Bar;

var bar = new Bar();
function something(bar: Bar) {

}

Thanks!

Comments

0

I'm not sure you want/need a module at all, just export the class:

class Bar {
   x: number;
}

/* Some more interfaces and classes to be used only in this module */

export = Bar;

and then in the consuming code:

import Bar = require('./Bar');
var bar = new Bar();

1 Comment

This method seems to require users use 'require'. This is not a problem, but I prefer to make things simplest and import Bar = Foo.Bar was what I exactly want! Thank you for answering :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.