☰ See All Chapters |
TypeScript Access Modifiers
TypeScript supports access modifiers public, private and protected which determine the accessibility of a class member as shown below: (These are only member level access modifiers and not class/function level and cannot be used with class/function/interface, can be used only with members of class/function/interface)
Accessible on | public | protected | private |
class | yes | yes | yes |
class children | yes | yes | no |
class instances | yes | no | no |
If an access modifier is not specified it is implicitly public as that matches the convenient nature of JavaScript. By default, a member of a TypeScript object can be accessed anywhere. That is, if you can access the object by name, you can access any of its properties or methods using dot notation Note that at runtime (in the generated JS) these have no significance but will give you compile time errors if you use them incorrectly. An example of each is shown below:
class Test { public x: number; private y: number; protected z: number; }
// EFFECT ON INSTANCES var test = new Test(); test.x; // okay test.y; // ERROR : private test.z; // ERROR : protected
// EFFECT ON CHILD CLASSES class TestChild extends Test { constructor() { super(); this.x; // okay this.y; // ERROR: private this.z; // okay } } |
All Chapters