call a protected property on an instance of a class in typescript

In TypeScript, you can call a protected property on an instance of a class by subclassing the class and accessing the protected property from within the subclass. Here's an example:

index.ts
class MyClass {
  protected myProperty: string = 'Hello, World!';
}

class MySubClass extends MyClass {
  public getMyProperty(): string {
    return this.myProperty;
  }
}

const myObj = new MySubClass();
console.log(myObj.getMyProperty()); // Output: Hello, World!
267 chars
13 lines

In this example, MyClass has a protected property myProperty. This means that the property can only be accessed from within the class itself or any subclasses.

MySubClass subclasses MyClass and adds a public method getMyProperty() which simply returns the value of myProperty. Since MySubClass is a subclass of MyClass, it has access to the protected property and can retrieve its value.

Finally, we create an instance of MySubClass and call its getMyProperty() method to retrieve the value of myProperty. The output of this code is Hello, World!.

gistlibby LogSnag