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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With