Home > Enterprise >  In Typescript, is it possible to override a superclass property's type without overriding the v
In Typescript, is it possible to override a superclass property's type without overriding the v

Time:11-22

I have a superclass property with a generic type, e.g.:

class Super {
  static get foo(): Record<string, any> {
    return ...
  }
}

I thought I could override the type like this:

class Sub extends Super {
  static foo: SubType;
}

However, this sets Sub.foo to undefined. I want Sub.foo to maintain the same value, but have a new type. Is this possible?

The type for Sub.foo is different because Super.foo depends on other static properties of the subclass.

I think implementing an interface should work, but it'll be good to know if there's another way.

CodePudding user response:

Use declare to avoid compiling the variable into the actual Javascript:

class Sub extends Super {
  declare static foo: SubType;
}
  • Related