0

I'm using TypeScript 3.4.5 and I have declared a class Person like following and created its instance person:

class Person {
    name: string;
    private personType: string = "Awesome Guy";
    protected age: number = 27;

    constructor(name: string, public userName: string) {
        this.name = name;
    }
}

const person = new Person("John", "john");
console.log(person); // {"userName":"john","personType":"Awesome Guy","age":27,"name":"John"}

But, when I printed the value of person object, it displayed values of private and protected members also. I can even access them like person.personType and person.age (though compiler gives error), it prints correct values and not undefined. What's wrong with this? Please help to clarify the doubt.

Gourav Pokharkar
  • 1,568
  • 1
  • 11
  • 33
  • 3
    Typescript compiles to Javascript which doesn't have such a notion as private and protected properties. The annotations are for compile-time errors, not for runtime safety. – Etheryte Jun 03 '19 at 11:13
  • FYI this will probably change when JS classes support private with `#` syntax, but that will probably not impact existing `private` field declarations – Titian Cernicova-Dragomir Jun 03 '19 at 11:14
  • But, when I don't initialize private and protected properties, they don't show up in object, not even as `undefined`. That seems little weird. – Gourav Pokharkar Jun 03 '19 at 11:16
  • Js private field proposal: https://github.com/tc39/proposal-private-fields and TS impact: https://github.com/microsoft/TypeScript/issues/31670 – Titian Cernicova-Dragomir Jun 03 '19 at 11:16
  • @GeniusGo that is a different issue, uninitialized fields never show up because JS has no clue the field exists until you initialize it – Titian Cernicova-Dragomir Jun 03 '19 at 11:17
  • @TitianCernicova-Dragomir, I'm little new to TypeScript, so sorry to ask, but do these **private** and **protected** access modifiers have real life use, if it doesn't encapsulates at runtime? – Gourav Pokharkar Jun 03 '19 at 11:20
  • @GeniusGo sure they do, the whole point of typescript is compile time checks. Much like a type does not have any run time error if violated but is still useful because of compile time checks – Titian Cernicova-Dragomir Jun 03 '19 at 11:22
  • Thanks, @TitianCernicova-Dragomir for clearing the doubt. – Gourav Pokharkar Jun 03 '19 at 11:24

0 Answers0