在继承的 class 方法中使用静态 属性

Using static property in inherited class method

这段代码使用 Babel 和 TypeScript 进行转换并按预期工作。

class ParentClass {
    static staticProp = true; 

    method() {
        console.log(this.constructor.staticProp);
    }
}

class ChildClass extends ParentClass {
    static staticProp = false;
}

(new ChildClass).method(); 

这里的要求是引用当前class的静态属性(通过this.constructor)而不是显式提及class,所以方法可以被继承并在子 classes.

中使用相关的静态 属性

Babel 没问题,TypeScript 也能编译,但是会抛出

error TS2339: Property 'staticProp' does not exist on type 'Function'.

编译中。

如何处理这种情况才能取悦 TypeScript 编译器?

如果您愿意牺牲类型检查,可以通过索引 属性:

来摆脱 TypeScript 编译器错误
console.log(this.constructor["staticProp"]);

TypeScript 目前仅支持 ClassName.staticPropertyName 语法。然而,an open issue要求简化它。

您还可以将 staticProp 包裹在 getter 中。这很麻烦,但至少感觉不像是语言黑客:

class ParentClass {
    static staticProp = true; 

    method() {
        console.log(this.staticProp);
    }

    get staticProp(): boolean { return ParentClass.staticProp; }
}

class ChildClass extends ParentClass {
    static staticProp = false; 

    get staticProp(): boolean { return ChildClass.staticProp; }
}

(new ChildClass).method(); 

我能够让 TypeScript 保持沉默

class ParentClass {
    static staticProp = true; 

    method() {
        console.log((<typeof ParentClass>this.constructor).staticProp);
    }
}