Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Public class extends a private class: not possible?

Tags:

typescript

I'm doing something very similar to this question:

TypeScript: make class visible inside module only

Except that I'm extending the private class. VS2012 throws a warning in my face: exported class MyExportedClass extends private class MyPrivateClass

My code looks like this:

module MyModule {
    class MyPrivateClass {
        constructor(public name: string) {
        }
        getName() {
            return this.name;
        }
    }

    export class MyExportedClass extends MyPrivateClass { // Error: exported class MyExportedClass extends private classMyPrivateClass
        constructor(name: string) {
            super(name);
        }        
    }
}

Am I right in my understanding that this is not possible?

like image 399
Ólafur Jens Ólafsson Avatar asked Dec 13 '12 20:12

Ólafur Jens Ólafsson


1 Answers

This isn't possible because it would allow anyone outside of the module to call members of your private class. You would basically be escalating the visibility of the class if they allowed it.

If you look at the code they generate you'll see that the private class literally isn't visible outside of the file because they don't make it a member off MyModule:

(function (MyModule) {
    var MyPrivateClass = (function () {
        function MyPrivateClass(name) {
            this.name = name;
        }
        MyPrivateClass.prototype.getName = function () {
            return this.name;
        };
        return MyPrivateClass;
    })();    
    var MyExportedClass = (function (_super) {
        __extends(MyExportedClass, _super);
        function MyExportedClass(name) {
                _super.call(this, name);
        }
        return MyExportedClass;
    })(MyPrivateClass);
    MyModule.MyExportedClass = MyExportedClass;    
})(MyModule || (MyModule = {}));

This doesn't mean the generated code wouldn't work but my expectation would be that the class would be visible to anyone within the module and given that a module can span multiple files that literally isn't possible.

The primary reason they're not allowing this is most likely because of the conceptual issue of escalating code visibility but I did want to point out there's a subtle technical gotcha as well.

like image 89
Steven Ickman Avatar answered Nov 15 '22 08:11

Steven Ickman