What is the equivalent of protected in TypeScript?

Solution 1:

Updates

November 12th, 2014. Version 1.3 of TypeScript is available and includes the protected keyword.

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

View the release notes for the protected keyword

class A {
    protected x: string = 'a';
}

class B extends A {
    method() {
        return this.x;
    }
}

Old Answer

TypeScript has only private - not protected and this only means private during compile-time checking.

If you want to access super.property it has to be public.

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;
    }
}

Solution 2:

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's not defined in the interface, this:

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 it in this playground.

You can also wrap it in a module while exporting only the interface, then from other exported methods you can return the instances (factory), that way the public scope of the 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'

Modified version in this playground.

I know it's not exactly what you asked for, but it's pretty close.

Solution 3:

at least at the moment (version 0.9) protected are not mentioned in the specs

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