Let's say I have a third-party base class structured like this:
export class Base {
[k: string]: any;
foo(): number;
bar(): number;
};
I need to inherit from this base class, but I want to remove the dynamic key in my object. Is there a way to achieve that?
For example, I would like to be able to safely write code like this:
class Child extends Base {
// Remove all dynamic keys
// Essentially make it inaccessible within my TypeScript code.
bzx(): number { return 3; }
}
const b = new Child();
b.foo() // OK;
b.bzx() // OK;
b.baz() // not allowed;
I attempted to follow the example for FunctionProperties<T>
mentioned in the TypeScript documentation, but encountered issues when handling T
with [k: string]:any
property.
Eventually, based on the advice provided in the accepted answer, I ended up duplicating the entire declaration file of the base class, excluding the:
[k: string]: any
Then, I transformed it into an interface rather than a class.
So, in practice, the process looked something like this:
import { Base } from 'Base';
import { IBase } from 'my/own/custom/IBase.ts'
class Child extends (Base as (new () => IBase)){ ... }
It could be argued that the approach above is slightly more refined because mixins played a role. Therefore, it resembles something along these lines:
function mix<C extends IBase>(base: Constructor<IBase>){
return class extends base { .... }
}
class Child extends mix(Base){ ... }