[英]How to specify return type of class constructor (e.g. using proxy)?
I'm pretty new to the Typescript world. 我是Typescript世界的新手。 Trying around with it a little more I stumbled across a problem when using a Proxy
as a returned value from a class constructor. 使用时,整个问题试图与它周围的多一点,我偶然发现Proxy
作为从类构造函数返回值。
Imagine the following code: 想象以下代码:
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 Container
type is intended to be used as a dependency injection container. Container
类型旨在用作依赖项注入容器。 So assigning the properties inside the Container
class is not possible due to the variable amount of services it will store. 因此,由于Container
将存储的服务数量可变,因此无法在Container
类内分配属性。
When validated it complains about missing properties sessionStorage
, session
and random
inside the Container
type when assigning arrow functions to them. 验证后,它会抱怨在为它们分配箭头功能时,在Container
类型内缺少sessionStorage
, session
和random
属性。
Property 'sessionStorage' does not exist on type 'Container'
I could of course assign a type to the container variable myself via as
or use a factory function, but find this approaches cumbersome for other people to use for example in case of library. 我当然可以自己通过as
或使用工厂函数将类型分配给容器变量,但是发现这种方法对其他人来说很麻烦,例如在使用库的情况下。
const container = new Container() as { [key: string]: any };
Is there an easier solution for this without the need of extra boilerplate code? 有没有更简单的解决方案,而无需额外的样板代码?
You can create an interface for it: 您可以为其创建一个接口:
interface SomeType {
[name: string]: any;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.