I have this class:
export class ResourceFactory {
AlgoliaAppId = "AlgoliaAppId";
// ...
private resetParams() {
this.AlgoliaAppId = "AlgoliaAppId";
// ...
}
public initTemplate(objectName, directiveArgs): Template {
this.resetParams(); // <-- Can I, in any possible way, prevent this line from running?
this.AlgoliaAppId = `${this.AlgoliaAppId}${objectName}`;
// ... [long function content which I don't want to duplicate]
}
}
I'm trying to extend the ResourceFactory
class: I want to change the AlgoliaAppId name and prevent resetParams
from running. (I cannot edit the original class).
Is there any way to override resetParams
even though it's private, or at least somehow monkey-patch the initTemplate method so it won't run the line this.resetParams
?
CodePudding user response:
There's no (clean) way to override a private
method from a base class you don't have control over. I tried some module augmentation to see if I could change the modifier to protected
but didn't have much luck; TypeScript seems to want all overloads to have the same modifier.
However, I was able to patch the prototype after the class declaration to hack in an overload, at the cost of including a @ts-expect-error
comment. Seems to be the path of least resistance for fighting with the compiler. Here's what an example subclass would look like:
class Example extends ResourceFactory {
AlgoliaAppId = "CustomName";
}
// @ts-expect-error
Example.prototype.resetParams = function resetParams() {
// your implementation
}
Here's a link to the playground as well.