ts中如何快速的引用静态属性

看如下一段代码所示

class Person {
  static actor = "actor";

  getActorLength() {
    return (this.constructor as typeof Person).actor.length;
  }

  actorToUpperCase() {
    return (<typeof Person>this.constructor).actor.toUpperCase();
  }
}

如果我需要引用类Person的静态属性,每次都要写很长一段代码来让typescript知道我引用的正确类型。引用的次数少还好,次数多了还这样做的话就会感觉很累。

可以修改为如下的这种方式,就可以解决反复写大段代码的问题。

class Person {
  "constructor": typeof Person;

  static actor = "actor";

  getActorLength() {
    return this.constructor.actor.length;
  }

  actorToUpperCase() {
    return this.constructor.actor.toUpperCase();
  }
}

修改之后,即使以后类名不叫做Person了,那么只修改"constructor": typeof Person就可以解决,其余的不用做任何改动。

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注