Ad

Typescript - Force Override Static Variable On Subclass

I have class A with a static variable I want to force each subclass of class A to override this static variable with some unique id.

Is it possible ? because the why we can force sub class to override some function/variable is using abstract keyword, but how static will work with abtract.

Following code will work - but I can't force the subclass to override...

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

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

any idea?

Ad

Answer

If you are looking for mandatory static properties in a derived class (aka. static abstract properties) there is no language support for this. There is a proposed feature for something like this here, but it's unclear if this will ever be implemented.

If you make A private inside a module, and you only export the type (not the class itself) and you also export a function that will require the fields and returns a class to inherit B from. You can achieve a measure of safety:

// 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);

NOTE

It's not clear from your code, in the title you say static field, but you don't declare the status_id field as static. If you just want an instance field to be required in derived classes you can just use the abstract keyword on that field:

abstract class A {
    public abstract status_id: string;
}

class B extends A  {
    status_id = "test" // error if missing
}
Ad
source: stackoverflow.com
Ad