My goal is to develop a factory for generating instances of MainType
. To achieve this, I want to reuse existing types (specifically the same instance) which are stored in the ItemFactory
.
class BaseType {
}
class MainType extends BaseType {
}
class ItemFactory {
items: { [type: string]: BaseType } = {};
get<T extends BaseType>(type: string): T | null {
let item = this.items[type];
if (!item) {
switch (type) {
case "main-type":
item = new MainType();
break;
default:
return null;
}
this.items[type] = item;
}
return item as T;
}
}
Is there a way to simplify the calling process?
itemFactory.get<MainType>("main-type"); // current call
// option 1
const resolvedType = itemFactory.get<MainType>();
// option 2
const resolvedType = itemFactory.get("main-type");
I prefer either option 1 or 2 (not both), so that I don't have to provide both an identifier and a type each time I want the resulting type to be correctly resolved.