DeployU
Interviews / Frontend Engineering / What are the different access modifiers in TypeScript?

What are the different access modifiers in TypeScript?

conceptual Object-Oriented Programming Interactive Quiz Code Examples

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?

Wrong Approach

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.

Right Approach

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

ModifierDescription
publicThe default access modifier. A public property can be accessed from anywhere.
privateA private property can only be accessed from within the class that it is defined in.
protectedA protected property can be accessed from within the class that it is defined in and from any subclasses that extend it.
readonlyA 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?