This project is read-only.

Simulating protected with modules & interfaces

Topics: General
Oct 6, 2012 at 7:19 PM

I've seen a couple of posts talking about the lack of 'protected' access in TypeScript and I totally agree, it's useful and I'd love to see it added to the language. I just thought I'd throw out a quick technique for how you can use modules and interfaces to simulate protected visibility:

module Foo {
	export class Foo
		private bar = new Bar();

		public getBar(): IBar {
	export interface IBar {
	class Bar implements IBar {
		doSomething() { }
		doSomethingProtected() { }

var foo = new Foo.Foo();
var bar = foo.getBar();

In the example code I have a Foo module that exposes a Foo class that anyone can create.  It also contains a Bar class but since it's not exported it's only visible to other classes within the Foo module.  What is exported is an IBar view of the Bar class. Since you have to go through Foo.getBar() to get an instance of IBar, code outside of the Foo module is only allowed to call the public non-protected members of Bar. The Foo class itself is free to call any method on Bar so you can consider any public members not exposed via IBar as protected.


Oct 31, 2012 at 9:56 PM

This is a nice idea. But the point about base and derived classes is there are likely to be many derived classes for any given base type.

According to this pattern all derived types will need to be declared in the same module.

So it doesn't scale very well.

Nov 1, 2012 at 7:43 PM

Yes... This is limited to classes within the same module.