add a private property to a class in typescript

To add a private property to a class in typescript, you can use the private access modifier. This will ensure that the property is only accessible within the class and cannot be accessed outside of it. Here's an example:

index.ts
class MyClass {
   private myPrivateProperty: string;

   constructor() {
      this.myPrivateProperty = "private property value";
   }
}
138 chars
8 lines

In this example, we have defined a private property called myPrivateProperty which can only be accessed within the MyClass class. When creating a new instance of MyClass, the private property can be set within the constructor.

Note that private properties cannot be accessed outside of the class, even by instances of the same class.

gistlibby LogSnag