geejay geejay - 1 month ago 7
TypeScript Question

What is the purpose of the public access modifier for classes in Typescript?

What is the purpose of the public access modifier for classes in Typescript?

What is the difference between

export class Thing {

public doStuff(){}

}


and

export class Thing {

doStuff(){}

}


It seems that the standard tsc JS output is exactly the same...

Answer

Your sample code means exactly the same in TypeScript. When you don't put a modifier public, private or protected on your member definition then TypeScript will choose the default one which is public.

That not make sense for Javascript because TypeScript transpiler will generate exactly the same code. But those modifiers will help you to encapsulate your class members and make them :

  • accessible outside of the class : public
  • only accessible in the class only : private
  • accessible in the class and the derived classes: protected

Again the generated Javascript will not contain the modifiers. That means that if someone get your Javascript code it will access to the members even if you defined them as private. The modifiers are only helpful in TypeScript and help developers to not access some class members.

Comments