Javascript 从超类(TS)中的子类引用静态字段

Javascript 从超类(TS)中的子类引用静态字段,javascript,typescript,inheritance,static,Javascript,Typescript,Inheritance,Static,在处理类和子类时,在基类中定义泛型方法并在其中使用特定于实例的变量是很常见的 但是,我不知道如何从基类到达方法中正确的静态类变量 以以下代码为例: abstract class Unit<T extends Symbol> { public static factors: {}; constructor( protected readonly type: T, protected value: number ) {} } c

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

但是,我不知道如何从基类到达方法中正确的静态类变量

以以下代码为例:

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];
    }
}
抽象类单元{
公共静态因素:{};
建造师(
受保护的只读类型:T,
保护值:数字
) {}
}
类能量扩展单元{
公共静态因素={
J:1,
kJ:1e3,
MJ:1e6,
GJ:1e9,
};
构造函数(值:数字,单位:keyof-typeof-Energy.factors='J'){
超级(能量符号,值*能量系数[单位]);
}
get(单位:能量类型的键。系数){
返回该值/能量系数[单位];
}
}
如果我们可以通过访问当前类的静态字段,将
get
方法放在基类内部,那么在添加更多类型的单元时,需要的代码会少得多

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


另外,有没有一种方法可以添加正确的类型?

我通过向基类添加一个额外的类型参数来解决这个问题,基类是所有允许的单位的并集

仍然需要为每个子类定义允许的单位,这可以通过
typefoounits=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);
    }
}
抽象类单元{
公共价值:数字;
建造师(
受保护的只读类型:T,
值:number,
公共单位:U
) {
this.value=value*this.constructor['units'][unit]
}
get(单位:U):编号{
返回this.value/this.constructor['units'][unit];
}
}
类型ENERGYNITS=类型Energy.units的键;
出口级能源单位{
公共静态单位={
J:1,
Wh:3.6e3,
};
构造函数(值:数字,单位:EnergyUnits='J'){
超级(能量符号、值、单位);
}
}

您正在寻找
这个.constructor
。(在TypeScript类型中,只需
this
)。顺便说一句,系数仅由单元的前缀确定,
this.constructor
根据TypeScript没有任何属性。除此之外,与键入相关的问题仍然没有答案。在这种情况下,请参阅,-TypeScript缺少对
此.constructor
的支持,但它仍然是您的
单元
类可能应该包含
公共静态单元:Record在这种情况下。我很乐意,除了“静态成员不能引用类类型参数”