What is equivalent to protected in TypeScript?

What is equivalent protected in TypeScript ?

I need to add some member variables to a base class that will only be used in derived classes .

+45
typescript
Mar 07 '13 at 15:55
source share
3 answers

Updates

November 12, 2014. Version 1.3 of TypeScript is available and includes a secure keyword.

September 26, 2014. The protected keyword has landed. This is currently a preliminary release. If you are using a very new version of TypeScript, now you can use the protected keyword ... the answer below is for older versions of TypeScript. Enjoy it.

View Release Notes for a Secure Keyword

 class A { protected x: string = 'a'; } class B extends A { method() { return this.x; } } 

Old answer

TypeScript has only private - it is not protected, and this means only confidentiality during compile time checking.

If you want to access super.property , it must be publicly available.

 class A { // Setting this to private will cause class B to have a compile error public x: string = 'a'; } class B extends A { method() { return super.x; } } 
+47
Mar 07 '13 at 16:44
source share

How about the following approach:

 interface MyType { doit(): number; } class A implements MyType { public num: number; doit() { return this.num; } } class B extends A { constructor(private times: number) { super(); } doit() { return super.num * this.times; } } 

Since the num variable is defined as public, this will work:

 var b = new B(4); b.num; 

But since it is not defined in the interface, it is:

 var b: MyType = new B(4); b.num; 

will result in The property 'num' does not exist on value of type 'MyType' .
You can try this in the playground .

You can also wrap it in a module when exporting only the interface, and then from other exported methods you can return instances (factory), so the total amount of variables will be โ€œcontainedโ€ in the module.

 module MyModule { export interface MyType { doit(): number; } class A implements MyType { public num: number; doit() { return this.num; } } class B extends A { constructor(private times: number) { super(); } doit() { return super.num * this.times; } } export function factory(value?: number): MyType { return value != null ? new B(value) : new A(); } } var b: MyModule.MyType = MyModule.factory(4); b.num; /// The property 'num' does not exist on value of type 'MyType' 

A modified version in this playground .

I know that this is not quite what you requested, but it is pretty close.

+4
Mar 28 '13 at 20:54
source share

at least at the moment (version 0.9) protected, not specified in specifications

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

+1
Jun 23 '13 at 19:54
source share



All Articles