Questions
What are the different access modifiers in TypeScript?
The Scenario
You are a frontend engineer at a fintech company. You are writing a new class that needs to have some private properties that can only be accessed by the class itself.
The Challenge
Explain the different access modifiers in TypeScript. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might not be aware of access modifiers. They might just make all the properties of a class public, which would not be a very good solution.
A senior engineer would be able to provide a detailed explanation of the different access modifiers in TypeScript. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Modifier | Description |
|---|---|
public | The default access modifier. A public property can be accessed from anywhere. |
private | A private property can only be accessed from within the class that it is defined in. |
protected | A protected property can be accessed from within the class that it is defined in and from any subclasses that extend it. |
readonly | A readonly property can only be set in the constructor. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use the private access modifier. This will ensure that the properties can only be accessed from within the class.
Step 3: Code Examples
Here are some code examples that show the difference between the different approaches:
class MyClass {
public myPublicProperty: string;
private myPrivateProperty: string;
protected myProtectedProperty: string;
readonly myReadonlyProperty: string;
constructor() {
this.myPublicProperty = "hello";
this.myPrivateProperty = "world";
this.myProtectedProperty = "foo";
this.myReadonlyProperty = "bar";
}
}
class MySubclass extends MyClass {
myMethod() {
console.log(this.myPublicProperty); // OK
// console.log(this.myPrivateProperty); // Error
console.log(this.myProtectedProperty); // OK
console.log(this.myReadonlyProperty); // OK
}
} Practice Question
You want to create a property that can be accessed by subclasses but not by the public. Which of the following would you use?