简体   繁体   中英

Is it possible to define this type in TypeScript?

I'm creating a TypeScript application. My idea is to pass a type of features to my app. Each feature is a class but it's not instantiated yet. There is also a special method "init" in my application where I want to pass the real feature objects.

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. 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 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
})

Playground Link

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();

Playground Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM