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

To access a private property on an instance of a class, you can create a public method in the same class which returns the value of the private property. Here's an example:

index.ts
class MyClass {
  private myPrivateProperty: string = 'private property value';

  public getMyPrivateProperty(): string {
    return this.myPrivateProperty;
  }
}

const myClassInstance = new MyClass();

console.log(myClassInstance.getMyPrivateProperty());
258 chars
12 lines

In this example, we define a private property myPrivateProperty in MyClass. We also define a public method getMyPrivateProperty() which simply returns the value of myPrivateProperty. Finally, we create an instance of MyClass and call the getMyPrivateProperty() method on it to access the private property.

Note that this approach is preferred over directly accessing the private property or using hacks to bypass the private keyword, as it encapsulates the private property within the class and prevents external code from accessing it directly.

gistlibby LogSnag