As I venture into the Typescript realm, I have encountered a challenge while experimenting with a Proxy
as a return value from a class constructor.
Consider the following code snippet:
class Container {
constructor() {
return new Proxy(this, containerProxyHandler);
}
}
const container = new Container();
container.sessionStorage = () => {
return new SessionStorage('SESSION_ID');
};
container.session = factory(() => {
return new Session(container.sessionStorage);
});
container.random = protected(() => {
return Math.random();
});
The purpose of the Container
type is to function as a dependency injection container. Therefore, assigning properties within the Container
class is not feasible due to the varying number of services it will hold.
During validation, an error arises regarding the absence of properties sessionStorage
, session
, and random
inside the Container
type when arrow functions are assigned to them.
Property 'sessionStorage' does not exist on type 'Container'
While I could manually assign a type to the container variable using as
or utilize a factory function, I find these approaches cumbersome for others to use, especially in the context of libraries.
const container = new Container() as { [key: string]: any };
Is there a simpler solution to this issue without resorting to additional boilerplate code?