Skip to main content

Modifiers

In TypeScript, modifiers are keywords that you can prepend to member declarations to alter their behavior in terms of accessibility, mutability, or uniqueness. These modifiers provide control over the visibility of class members to other parts of the code and control over the immutability of properties in objects and classes.

Accessibility Modifiers

These modifiers control the visibility or accessibility of class members (properties, methods) to other parts of your code.

  1. public: This is the default accessibility for class members. Public members are accessible from any location.

  2. private: Members marked as private can only be accessed within the class that defines them. TypeScript enforces this rule at compile time.

  3. protected: Protected members are accessible within the class they're defined in and by instances of derived classes. They are more accessible than private members but less so than public ones.

Mutability Modifier

This modifier is used to make properties of objects or classes immutable after their initial assignment.

  1. readonly: This keyword makes a property immutable, meaning its value cannot be changed after it is initially set. It can be used in classes, interfaces, and object literals.

Static Modifier

This modifier is applied to define properties or methods on the class itself rather than on instances of the class.

  1. static: Static members are accessed directly on the class itself rather than on instances of the class.

Abstract Modifier

This modifier is used in classes and class members that cannot be instantiated directly and need to be extended or implemented by some other class.

  1. abstract: Abstract classes can be used as a base class for other classes but cannot be instantiated on their own. Abstract methods defined in abstract classes do not contain an implementation and must be implemented by derived classes.

Unique Symbols

While not a modifier in the traditional sense, unique symbol is a special construct in TypeScript for creating unique symbol types.

  1. unique symbol: A unique symbol is a subtype of the symbol type that guarantees symbol uniqueness. This is used for creating unique property keys and is often combined with the const declaration.

Optional Modifier

Used in interfaces and object types to mark properties as optional.

  1. ?: When appended to a property name in an interface or type declaration, it indicates that the property is optional and may or may not be present.