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.ts267 chars13 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