打字稿-强制覆盖子类上的静态变量

Typescript - force override static variable on subclass

我有 class A 和一个静态变量 我想强制 class A 的每个 subclass 覆盖这个静态变量 有一些独特的ID。

可能吗? 因为我们可以强制 sub class 覆盖某些 function/variable 的原因是使用 abstract 关键字,但是 static 如何与 abtract.

一起工作

以下代码可以工作 - 但我不能强制子class覆盖...

abstract class A {
    protected static _id: string;
    abstract setStaticProp(): void;
}

class B extends A {
    protected static id= 'test';
}

有什么想法吗?

如果您在派生的 class 中寻找强制性静态属性(也称为静态抽象属性),则没有语言支持。有一个类似 here 的提议功能,但不清楚是否会实现。

如果您在模块中将 A 设置为私有,并且您只导出类型(而不是 class 本身),并且还导出一个需要字段和 returns 一个 class 从 B 继承。您可以获得安全措施:

// The actual class implementation
abstract class _A {
    public static status_id: string;
}
export type A = typeof _A; // Export so people can use the base type for variables but not derive it
// Function used to extend the _A class
export function A(mandatory: { status_id : string})  {
    return class extends _A {
        static status_id = mandatory.status_id
    }
}

// In another module _A is not accessible, but the type A and the function A are
// to derive _A we need to pass the required static fields to the A function
class B extends A({ status_id: 'test' }) {

}

console.log(B.status_id);

注意

从你的代码中不清楚,在标题中你说静态字段,但你没有将 status_id 字段声明为 static。如果您只想在派生的 classes 中需要一个实例字段,您可以在该字段上使用 abstract 关键字:

abstract class A {
    public abstract status_id: string;
}

class B extends A  {
    status_id = "test" // error if missing
}