TypeScript - Difference between Private and Protected Variables

Solution 1:

It's the same as in other OO languages.
Private methods/members are accessible only from inside the class.
Protected methods/members are accessible from inside the class and extending class as well.

class A {
    private x: number;
    protected y: number;

    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }

    getX(): number {
        return this.x;
    }

    getY(): number {
        return this.y;
    }
}

class B extends A {
    multiply(): number {
        return this.x * this.y;
    }
}

Notice that in class A there's access to both (private) this.x and (protected) this.y.
But in class B there's only access to this.y and this.x has this error:

Property 'x' is private and only accessible within class A

(you can see the error in playground)

What's important to understand though is that this is only true to typescript.
In javascript those members are accessible to anyone with a reference to the instance.

Solution 2:

PRIVATE Method:

When a member is marked private, it cannot be accessed from outside of its containing class.

PROTECTED Method:

The protected modifier acts much like the private modifier with the exception that members declared protected can also be accessed within deriving classes.

There is one more point to add regarding Protected variables:

when a base class variable is protected we cannot use its variable from derived class directly.

For e.g:

class Car{
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Mercedes extends Car{
    private noOfWheels: number;

    constructor(name: string, noOfWheels: number) {
        super(name);
        this.noOfWheels= noOfWheels;
    }

    public getIntro() {
        return `Hello, This is my ${this.name} and I have ${this.noOfWheels} wheels.`;
    }
}

let myCar= new Mercedes ("COOL Car", 4);
console.log(myCar.getIntro());  //Hello, This is my COOL Car and I have 4 wheels.
console.log(myCar.name); // Error!! , Property 'name' is protected and only accessible within class 'Car' and its subclasses.

we can’t use variable name directly from outside of Car class, we can still use it from within an instance method of Mercedes because Mercedes derives from Car.

Solution 3:

protected works in TypeScript very similarly like it does from C#. The TypeScript release notes document it as such:

The new protected modifier in classes works like it does in familiar languages like C++, C#, and Java. A protected member of a class is visible only inside subclasses of the class in which it is declared

Whereas private only lets you have access to the immediate class type. Private members are not visible to subclasses.