Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we access a private variable in another class in typescript

Tags:

typescript

class Animal {
    private name:string;
    public Firstname:string;
    constructor(theName: string)
    {
        this.name = theName;
        this.Firstname=theName;
    }
}

class Tiger {
    function sample(){
        Animal animalName=new Animal('Tiger');
        document.body.innerHTML = animalName.name;
    }
    sample();
}

Hi am new to this TypeScript here in animal class I've created a private variable name I used that in class constructor. Now in class Tiger I created the instance for Animal class and able to access that private variable.

My question is in Java if we do we will get error. But in TypeScript (because TypeScript supports OOPS) we are not getting any error moreover it is giving the value how is it possible?

like image 397
KPR Krishnachaitanya Avatar asked Feb 25 '16 11:02

KPR Krishnachaitanya


2 Answers

First - your code will not compile. TypeScript will check the accessibility of the name and give you an error. Check yourself at typescript playground: playground

Second - it is possible access private properties if you will remove typescript checks, for example:

console.log((<any>animalName).name)

This works due to the fact that natively JavaScript does not have a notion of private properties. And as TypeScript is compiled to JavaScript you have such a possibility.

like image 106
Amid Avatar answered Sep 22 '22 02:09

Amid


An alternative to using the as any trick that Amid posted is to use the string index notation, which is an intentional escape hatch for accessing private members:

console.log(animalName['name']);

This has the advantage of being type-safe, so if you ever remove name, you'll get a compiler error here.

like image 43
Oleg Vaskevich Avatar answered Sep 23 '22 02:09

Oleg Vaskevich