【问题标题】:Referring to static fields from subclasses in superclass (TS) [duplicate]引用超类(TS)中子类的静态字段[重复]
【发布时间】:2021-08-03 19:15:57
【问题描述】:

在使用类和子类时,在基类中定义泛型方法并在其中使用实例特定变量是很常见的。

但是,我不知道如何从基类的方法中访问正确的 static 类变量。

以下面的代码为例:

abstract class Unit<T extends Symbol> {
    public static factors: {};

    constructor(
        protected readonly type: T,
        protected value: number
    ) {}
}

class Energy extends Unit<typeof EnergySym> {

    public static factors = {
        J: 1,
        kJ: 1e3,
        MJ: 1e6,
        GJ: 1e9,
    };

    constructor(value: number, unit: keyof typeof Energy.factors = 'J') {
        super(EnergySym, value * Energy.factors[unit]);
    }

    get(unit: keyof typeof Energy.factors) {
        return this.value / Energy.factors[unit];
    }
}

如果我们可以将get 方法放在基类中,通过访问 current 类的静态字段,添加更多类型的单元时需要更少的代码。

在 Python 中,例如,您可以使用 self.__class__.foo。有 JavaScript 等价物吗?

另外,有没有办法为此添加正确的类型?

【问题讨论】:

标签: javascript typescript inheritance static


【解决方案1】:

我已经设法通过向基类添加一个额外的类型参数来解决它,该类型参数是所有允许单位的联合。

仍然需要为每个子类定义允许的单位,这可以使用type FooUnits = keyof typeof Foo.units 完成,假设它们被定义为类本身的静态字段。

人们仍然可以想象,这可以用更少的代码来完成,但据我所知,没有 TS 支持。

abstract class Unit<T extends Symbol, U> {

    public value: number;

    constructor(
        protected readonly type: T,
        value: number,
        public unit: U
    ) {
        this.value = value * this.constructor['units'][unit]
    }

    get(unit: U): number {
        return this.value / this.constructor['units'][unit];
    }
}

type EnergyUnits = keyof typeof Energy.units;

export class Energy extends Unit<typeof EnergySym, EnergyUnits> {

    public static units = {
        J: 1,
        Wh: 3.6e3,
    };

    constructor(value: number, unit: EnergyUnits = 'J') {
        super(EnergySym, value, unit);
    }
}

【讨论】:

  • 在这种情况下,您的 Unit 类可能应该包含 public static units: Record&lt;U, number&gt;;
  • 我很乐意,除了“静态成员不能引用类类型参数”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
相关资源
最近更新 更多