Prompt Detail:
In TypeScript, the access modifiers public
, private
, readonly
, and protected
are used to control the accessibility of class properties and methods.
- Public:
The
public
keyword indicates that the property or method can be accessed from anywhere, including outside the class. If no access modifier is specified, then the property or method is considered public by default.
Example:
csharpclass MyClass {
public myProperty: string;
public myMethod(): void {
console.log("Hello World!");
}
}
const obj = new MyClass();
obj.myProperty = "Hello";
obj.myMethod(); // Output: "Hello World!"
- Private:
The
private
keyword indicates that the property or method can only be accessed within the class. It cannot be accessed from outside the class, not even from subclasses.
Example:
vbnetclass MyClass {
private myProperty: string;
private myMethod(): void {
console.log("Hello World!");
}
}
const obj = new MyClass();
obj.myProperty = "Hello"; // Error: Property 'myProperty' is private and only accessible within class 'MyClass'.
obj.myMethod(); // Error: Property 'myMethod' is private and only accessible within class 'MyClass'.
- Readonly:
The
readonly
keyword indicates that the property can only be assigned a value once and cannot be changed afterwards. It can be accessed from anywhere, but cannot be modified.
Example:
typescriptclass MyClass {
public readonly myProperty: string;
constructor() {
this.myProperty = "Hello";
}
}
const obj = new MyClass();
obj.myProperty = "World"; // Error: Cannot assign to 'myProperty' because it is a read-only property.
console.log(obj.myProperty); // Output: "Hello"
- Protected:
The
protected
keyword indicates that the property or method can be accessed within the class and its subclasses, but not from outside the class hierarchy.
Example:
csharpclass MyBaseClass {
protected myProperty: string;
protected myMethod(): void {
console.log("Hello World!");
}
}
class MySubClass extends MyBaseClass {
public myPublicMethod(): void {
this.myProperty = "Hello";
this.myMethod();
}
}
const obj = new MySubClass();
obj.myProperty = "World"; // Error: Property 'myProperty' is protected and only accessible within class 'MyBaseClass' and its subclasses.
obj.myMethod(); // Error: Property 'myMethod' is protected and only accessible within class 'MyBaseClass' and its subclasses.
obj.myPublicMethod(); // Output: "Hello World!"
In summary, access modifiers in TypeScript provide a way to control the accessibility of class members and ensure the integrity of class data.
Add a comment