从typescript中具有相同父类的其他实例访问受保护的方法

从typescript中具有相同父类的其他实例访问受保护的方法,typescript,oop,protected,Typescript,Oop,Protected,我正在将代码从PHP移植到NodeJs Typescript。 我遇到了以下简化的PHP代码 <?php class A { protected function protectedData() { return 'accessible'; } } class B extends A { public function extractTest($anInstanceOfA) { return $anInstanceOfA->p

我正在将代码从PHP移植到NodeJs Typescript。 我遇到了以下简化的PHP代码

<?php
class A {
    protected function protectedData() {
        return 'accessible';
    }
}
class B extends A {
    public function extractTest($anInstanceOfA) {
        return $anInstanceOfA->protectedData();
    }
}
$instanceA = new A();
$instanceB = new B();
echo $instanceB->extractTest($instanceA);

<?php
class A {
    protected function protectedData() {
        return 'accessible';
    }
}
class B extends A {
    public function extractTest($anInstanceOfA) {
        return $anInstanceOfA->protectedData();
    }
}
$instanceA = new A();
$instanceB = new B();
echo $instanceB->extractTest($instanceA);
错误:属性“protectedData”受保护,只能通过类“B”的实例访问。2446

有没有办法在Typescript中实现这一点,或者PHP和Typescript中受保护的方法之间有很大区别?

来自:

受保护修饰符的作用与私有修饰符非常相似,只是声明为受保护的成员也可以在派生类中访问

在上面的例子中,您使用protectedData作为函数参数anInstanceOfA的方法,该参数恰好是基类型a。但是您不能通过this.protectedData访问派生类B中的protectedData,所以TS在这里喊叫。哪些有效,哪些无效:

class B extends A {
  public extractTest(anInstanceOfA: A, instanceOfB: B): string {
    anInstanceOfA.protectedData() // ✖, protected member of arg with base class 
    instanceOfB.protectedData() // ✔, protected member of arg with *same* class 
    this.protectedData(); // ✔, (derived) protected member via `this`
    return anInstanceOfA["protectedData"]() // escape-hatch with dynamic property access
  }
}
因此,您可以将protectedData声明为public,也可以使用转义图案填充,这将使受保护的成员可以通过使用括号表示法的动态属性访问来访问

anInstanceOfA["protectedData"]()
从:

受保护修饰符的作用与私有修饰符非常相似,只是声明为受保护的成员也可以在派生类中访问

在上面的例子中,您使用protectedData作为函数参数anInstanceOfA的方法,该参数恰好是基类型a。但是您不能通过this.protectedData访问派生类B中的protectedData,所以TS在这里喊叫。哪些有效,哪些无效:

class B extends A {
  public extractTest(anInstanceOfA: A, instanceOfB: B): string {
    anInstanceOfA.protectedData() // ✖, protected member of arg with base class 
    instanceOfB.protectedData() // ✔, protected member of arg with *same* class 
    this.protectedData(); // ✔, (derived) protected member via `this`
    return anInstanceOfA["protectedData"]() // escape-hatch with dynamic property access
  }
}
因此,您可以将protectedData声明为public,也可以使用转义图案填充,这将使受保护的成员可以通过使用括号表示法的动态属性访问来访问

anInstanceOfA["protectedData"]()