Prompt Title: Access Modifiers in TypeScript

Created 1 year ago
Votes 0
Views 319 times
IT
0

Prompt Detail:

In TypeScript, the access modifiers public, private, readonly, and protected are used to control the accessibility of class properties and methods.

  1. 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:

csharp
class MyClass { public myProperty: string; public myMethod(): void { console.log("Hello World!"); } } const obj = new MyClass(); obj.myProperty = "Hello"; obj.myMethod(); // Output: "Hello World!"
  1. 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:

vbnet
class 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'.
  1. 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:

typescript
class 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"
  1. 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:

csharp
class 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.

avatar
Dilshod
Shared 2 prompts
Created 1 year ago

Leave a Comment

Related Tag Prompts

0
0
0
0
TypeScript Code Analysis.
1 year ago 2023-03-23 22:13:32 Haidar Chikh
0
0
C++ Syllabus.
1 year ago 2023-04-07 16:19:44 Mahesh Rawat
0
0
Using RxJS in Angular
1 year ago 2023-04-25 01:57:06 Vijayakumar
0
0
0
0
global.d.ts
8 months ago 2024-03-15 07:55:08 Sam