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

我正在将代码从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);

在沙箱中运行它会产生回显“可访问”。

我用Typescript编写了相同的代码,但这似乎不起作用...

class A {
  protected protectedData(): string {
    return 'accessible';
  }
}

class B extends A {
  public extractTest(anInstanceOfA: A): string {
    return anInstanceOfA.protectedData();
  }
}

const instanceA = new A();
const instanceB = new B();


console.log(instanceB.extractTest(instanceA));

错误:属性'protectedData'受保护,并且只能通过类'B'的实例进行访问。(2446)

在Typescript中是否可以实现此目的,或者PHP和Typescript中的受保护方法之间有很大区别?

xiaojiankunzhuxi 回答:从打字稿中具有相同父类的其他实例访问受保护的方法

来自docs

protected修饰符的行为与private修饰符非常相似,不同之处在于声明为受保护的成员也可以在派生类中访问

在上述情况下,您使用protectedData作为函数参数anInstanceOfA的方法,该参数恰好是基本类型A。但是您不会访问protectedData派生类B内的this.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或使用转义符,这将使protected成员可以通过带有括号符号的动态属性访问来访问。

anInstanceOfA["protectedData"]()

Playground sample to try it out

本文链接:https://www.f2er.com/2612804.html

大家都在问