代码之家  ›  专栏  ›  技术社区  ›  john Smith

typescript-强制覆盖子类上的静态变量

  •  0
  • john Smith  · 技术社区  · 8 年前

    我有一个带有静态变量的类A 我想强制类A的每个子类重写这个静态变量 带有一些唯一的ID。

    有可能吗? 因为我们可以强制子类重写某些函数/变量的原因是使用了abstract关键字,但是static如何处理abtract。

    下面的代码可以工作-但我不能强制子类重写…

    abstract class A {
        protected static _id: string;
        abstract setStaticProp(): void;
    }
    
    class B extends A {
        protected static id= 'test';
    }
    

    知道吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    8 年前

    如果要在派生类(aka)中查找强制静态属性。静态抽象属性)。有一个像这样的建议功能 here 但目前还不清楚这是否会被实施。

    如果你 A 在模块内部是私有的,并且只导出类型(而不是类本身),还导出一个需要字段并返回要继承的类的函数 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 .如果只希望在派生类中需要实例字段,则可以使用 abstract 该字段的关键字:

    abstract class A {
        public abstract status_id: string;
    }
    
    class B extends A  {
        status_id = "test" // error if missing
    }
    
    推荐文章