TypeScript – Difference between Private and Protected Variables

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)