Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import.
Here is the structure of my folders:
.
├── DynamicAdvertising
│ ├── asTemporalSlots.ts
│ └── index.ts
└── index.ts
I wanted to achieve the following functionality:
import Personalisation from "./DynamicAdvertising";
/** Here Personalisation should not have the method 'asTemporalSlots' **/
import "./DynamicAdvertising/asTemporalSlots";
/** Here Personalisation should have it **/
The Personalisation
class had the following setup:
export default class Personalisation {
constructor(private response: Response) {}
static async fetch(request: PersonalisationRequest<any>) {
if (!(request instanceof PersonalisationRequest)) {
throw new Error('Wrong request. Cannot proceed.');
}
const response = await fetch(request);
return new Personalisation(response);
}
/* ... */
}
Creating an instance through a static method was the approach taken. To extend Personalisation
in asTemporalSlots
, I followed this pattern:
import Personalisation from ".";
declare module "." {
export default interface Personalisation {
asTemporalSlots(this: Personalisation): any
}
}
Personalisation.prototype.asTemporalSlots = async function asTemporalSlots(): AdvSlots[] {
...
}
While extending worked without issues, accessing the this.response
property, which was marked as private
, posed a challenge when using the extended method. When directly adding asTemporalSlots
to Personalisation
, it could be used without any problems. The question arises - why does extending the prototype cause issues with private properties? How can this be resolved while keeping the response private?
Grateful for any insights and suggestions. Thank you!