如何通过非静态方法获取静态属性-打字稿

问题描述 投票:0回答:1

我具有与以下代码类似的类。

class Base {
  protected abstract static link: string;

  public fetch(){
    // Solution need
    const link =  self.link;

    // Do other things with link
  }
}

class A extends Base {
  protected static link = 'some link'
}

class B extends Base {
 protected static link = 'other link'
}

并且我需要定义一个通用函数来根据链接值为每个模型获取数据。我无法将静态link值更改为属性。由于某些静态方法使用了此链接值。

我已经尝试过Base.link。但是我无法使用此方法访问子类的原始值。预先感谢!

typescript es6-class
1个回答
2
投票
class Base {
  protected static link: string;

  public fetch(){
    const self = Object.getPrototypeOf(this).constructor;
    return self.link
  }
}

class A extends Base {
  static link = 'some link'
}

class B extends Base {
  static link = 'other link'
}

const b = new B();
const a = new A();
console.log(b.fetch()) // other link
console.log(a.fetch()) // some link

https://stackblitz.com/edit/typescript-kwsejh

© www.soinside.com 2019 - 2024. All rights reserved.