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.
-
public
: This is the default accessibility for class members. Public members are accessible from any location. -
private
: Members marked as private can only be accessed within the class that defines them. TypeScript enforces this rule at compile time. -
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.
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.
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.
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.
unique symbol
: Aunique 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 theconst
declaration.
Optional Modifier​
Used in interfaces and object types to mark properties as optional.
?
: 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.