TypeScript: use private or public in constructor

Actually in your first example the explicit assignment is not needed at all:

export class XPTO {
   constructor(public nav: NavController) {
       // This line is not required.
       // this.nav = nav;
       this.someFunction();
   }
   someFunction(){
       console.log(this.nav); // Prints out the NavController.
   }
}

Whenever you specify public or private on a constructor parameter a corresponding public/private variable is created on the class and filled with the value of the parameter.

So really, the only difference of the two code samples is that one is private and the other one is public.

The resulting JavaScript will be the same. However, the compiler will throw an error, if you are trying to access private variables in your code.


public and private, as a lot of Typescript features, are only TypeScript modifiers. I'm not sure the compiler names these variables exactly the same, but from a JavaScript point of view, the code will be essentially the same.

The interest of Typescript is to give you features like type checking, it doesn't necessarily always modifies the outputted code.