Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: make class visible inside module only

Tags:

typescript

Have a look at the following code:

module MyModule {
    class MyPrivateClass {
        ...
    }

    export class MyPublicClass {
        private var: MyPrivateClass; // MyPrivateClass is unknown
    }
}

I want MyPrivateClass to be only visible inside MyModule, specifically for internal use in MyPublicClass. Outside MyModule, only MyPublicClass should be visible. I figured that the above layout should do but VS complains that MyPrivateClass isn't visible inside MyPublicClass. Adding export before the definition of MyPrivateClass makes it visible to MyPublicClass but then it's also visible from the outside.

Is there a way to make it visible to MyPublicClass only?

Thank you.

like image 915
vexator Avatar asked Oct 08 '12 12:10

vexator


2 Answers

Here is a working example that shows the private class, the public class, using the private class from the public class and attempting to use the private class, which generates an error.

If you still get an error, are you able to disclose the name you are trying to use for the module that causes the problem?

module MyModule {
    class MyPrivateClass {
        doSomething() {
            return 1;
        }
    }

    export class MyPublicClass {
        private x = new MyPrivateClass();

        someFunction() {
            return this.x.doSomething();
        }
    }
}

var examplePublic = new MyModule.MyPublicClass();
var result = examplePublic.someFunction(); // 1

var examplePrivate = new MyModule.MyPrivateClass(); // error
like image 112
Fenton Avatar answered Oct 24 '22 01:10

Fenton


If you want it to be private in the emmitted JavaScript you can do this by moving the private clas instance to inside the module, but not in side the exported class.

module MyModule {
    class MyPrivateClass {
        prop1: number = 1;
    }

    var foo: MyPrivateClass = new MyPrivateClass();

    export class MyPublicClass {
        someMethod(){
            var bar = foo.prop1;
        }
    }
}

var x = new MyModule.MyPublicClass();
like image 40
John Papa Avatar answered Oct 24 '22 02:10

John Papa