Codecademy Logo

TypeScript Class Types

TypeScript Class Types

Class types provide compilation checks for different property and method privacy levels, which allows us to specify which properties and methods of a class are accessible outside of the class.

The public Type

In TypeScript, every class property and method is public by default. The public keyword is useful for readability and maintaining a consistent style within a codebase. Unlike other class types, the public keyword does not affect how TypeScript compiles code.

The private Type

The private type in TypeScript specifies that a property or method in a class should not be accessed outside of the class. When private is used to mark a field, it cannot be called in a derived class or on a class instance. If a private method or property is called in a derived class or class instance, TypeScript will generate an error during compilation.

The readonly Type

The readonly type marks a property or method in a class as unchangeable after initialization. When the readonly type is applied, the property or method can be assigned in the class’ constructor() method, but may not be reassigned at any other time.

The protected Type

The protected type marks a property or method in a class as accessible only by the class itself or by derived classes. When the protected type is applied, instance of classes may not access the protected property or method.

Learn More on Codecademy