I am facing a challenge in creating a class that accepts a factory
function as one of its parameters in the constructor, which is then used to create instances of another class. The implementation below is written in JavaScript.
// item to create
class Item{}
function factory(someData){
return new Item()
}
class Repository{
constructor(factory){
this.factory = factory
}
createItem(optionalData){
return this.factory(optionalData)
}
}
The objective now is for the Repository
class to accept a generic
item, and ensuring that the factory function creates that generic item.
My struggle lies in extracting the parameters from the factory
property and using them within the createItem
method. I want the createItem
method to mirror the arguments of the factory
function.
class Item {
constructor(public data:{id:string,name:string}){
}
}
// trying to type the factory function
export type ModelFactory<TModel> = (...args:any[]) => TModel
class Collection<TModel >{
constructor(public factory:ModelFactory<TModel>){}
// attempting to extract factory function parameters
createItem(data?:Parameters<ConstructorParameters<typeof Collection>[0]>[0]){
return this.factory(data)
}
}
// implementation
const createItemFactory:ModelFactory<Item> = function (data:{id:string,name:string}){
return new Item(data)
}
const coll = new Collection<Item>(createItemFactory)
// arguments passed to createItem() should be strongly typed
const itemInstance = coll.createItem(1)
Issues:
- When calling
coll.createItem()
, the arguments are typed asany
- The
factory
function could have a signature with no arguments.
I am finding it challenging to address these scenarios.