I am currently using factory pattern in my project, below is the minimal reproducible code
class A {
constructor(public name: string) {}
}
class B {
constructor(public age: number, public address: string) {}
}
type FactoryMap = {
A: A,
B: B
}
const map = {
A,
B
}
function create<T extends keyof FactoryMap>(name: T, ...params: ConstructorParameters<typeof FactoryMap[T]>): FactoryMap[T] {
switch (name) {
case "A":
return new A(...params);
case "B":
return new B(...params);
}
}
function create2<T extends keyof typeof map>(name: T, ...params: ConstructorParameters<typeof map[T]>): typeof map[T] {
return new map[name](...params);
}
I've tried two different functions, but neither could work.
The first one said Type 'A' is not assignable to type 'A & B', but I wonder FactoryMap[T] should be A | B.
The second one's error is Type 'A | B' is not assignable to type '{ A: typeof A; B: typeof B; }[T]', I know why but I can't infer A | B using the object map.
Does anyone has solutions on those two functions?
createfunction? instead of calling create<A> just create an object withnew A(...)command.document.createElement("div" | "span" | "p"), I can easily create instances of different types.