Can we access a private variable in another class in 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, new to this typeScript here in the animal class. I created the name of a private variable that I used in the constructor of the class. Now, in the Tiger class, I created an instance of the Animal class and was able to access this private variable.

My question is in java, if we do this, we will get an error. But in typeScript (because typeScript supports oops), we get no error, moreover, it gives a value, how is this possible?

+5
source share
1 answer

First, your code will not compile. Typescript will check the availability of the name and give you an error. Test yourself at the Typescript Playground: playground

Second - you can access private properties if you delete Typescript checks, for example:

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

This works because initially javascript does not have the concept of private properties. And since Typescript is compiled into javascript, you have such an opportunity.

+11
source

Source: https://habr.com/ru/post/1243843/


All Articles