1

I am learning access modifiers in typescript, I have the following class .

 export class Person {
      private get fullName() {
        return this.firstName + '' + this.lastname;
      }
      constructor(public firstName, public lastname) {

      }
    }
    const name = new Person('jim', 'jonson');
    alert(name.fullName);

When I hover on full name Intellisense gives me the following error

Property 'fullName' is private and only accessible within class 'Person'.

Can somebody explain me why full name is displayed on my browser?

Shreyas
  • 999
  • 6
  • 19
The Dead Man
  • 6,258
  • 28
  • 111
  • 193
  • 3
    TypeScript errors do not prevent compilation into JavaScript, so they are effectively warnings of incorrect usage that could potentially lead to unintended behavior in the resulting JavaScript. – Patrick Roberts Jul 12 '18 at 20:34
  • 1
    Thanks for explanation bro apreaciate so for what your saying , meaning Js lacks privacy at all? – The Dead Man Jul 12 '18 at 20:36
  • 2
    `Js lacks privacy at all` [Javascript has privacy, it's all about implementation](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes). That being said, the Access Modifiers you're specifying are not *Javascript* they are *Typescript*.. huge difference. – Erik Philips Jul 12 '18 at 20:40
  • @ErikPhilips thanks for the link now understand it , i was confused little bit ) u can put as answer I will accept it . – The Dead Man Jul 12 '18 at 20:54
  • What IDE are you using? The IDE intellisense can display that as info, but if it marks as error than the IDE has a bug. – unional Jul 12 '18 at 20:55
  • visual code, I tried even changing to this `alert(name['fullName']);` also works so its not about ide read the link provided by another fella above , there is complete expalantion about this. – The Dead Man Jul 12 '18 at 20:57
  • why is your getter *private* but the attribute it encapsulates is *public*? That's backwards. – juanpa.arrivillaga Jul 12 '18 at 22:41
  • @juanpa.arrivillaga codes is okay nothing wrong I was just wondering about the privacy of js whatsover – The Dead Man Jul 12 '18 at 22:45

1 Answers1

0

Access modifiers in typescript is typescript feature rather than javascript feature.

So when you compile .ts to .js this kind of feature is over-ridden; like interfaces.

Maybe in future releases, JavaScript will have access modifiers .

During compilation you will get the error

Property 'fullName' is private and only accessible within class 'Person'.

You can change this compiler option in tsconfig.ts file

  "compilerOptions": {
    "noEmitOnError": true
}

This will stop typescript compiler if there is an error.

Happy Coding;

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91