[英]Is it possible to define this type in TypeScript?
I'm creating a TypeScript application.我正在创建一个 TypeScript 应用程序。 My idea is to pass a type of features to my app.我的想法是将一种功能传递给我的应用程序。 Each feature is a class but it's not instantiated yet.每个功能都是 class,但尚未实例化。 There is also a special method "init" in my application where I want to pass the real feature objects.在我的应用程序中还有一个特殊的方法“init”,我想在其中传递真实的特征对象。
How to define this?这个怎么定义?
If I define my generic type like:如果我像这样定义泛型类型:
Application<F extends Record<string, Feature>>
Then TS wants me to pass instances to my type.然后 TS 要我将实例传递给我的类型。 How can I define that this type is a record of classes and after that will I be able to create a new type which will reflect the structure of original type but with instances?我如何定义这种类型是类的记录,然后我将能够创建一个新类型来反映原始类型的结构但具有实例?
To pass in a class you need to pass in the constructor of the class. You can do this using a constructor signature (similar to a function signature, just with the keyword new
in front of it)要传入 class,您需要传入 class 的构造函数。您可以使用构造函数签名来执行此操作(类似于 function 签名,只是在其前面加上关键字new
)
class Application<F extends Record<string, new () => Feature>> {
constructor(feautures: F) {
for(let key in feautures) {
let f= new feautures[key]();
f.init()
}
}
}
new Application({
FeatureA,
FeatureB
})
Or if you want to have easier access to the instance types you could also use:或者,如果您想更轻松地访问实例类型,您还可以使用:
class Application<F extends Record<string, Feature>> {
featureInstances: F;
constructor(feautures: { [P in keyof F]: new () => F[P] }) {
this.featureInstances = {} as F
for(let key in feautures) {
let f= new feautures[key]();
f.init()
this.featureInstances[key] = f
}
}
}
let app = new Application({
FeatureA,
FeatureB
})
app.featureInstances.FeatureA.methodA();
app.featureInstances.FeatureB.methodB();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.