I want to create a function that will create a different class by passing different args ,
but I am getting an error in the code below;
It looks like even though I specify the generic, typescript can't understand it
type ClassAOptions = {
fooA: string;
barA: string;
};
class ClassA {
constructor(options: ClassAOptions) {}
static new(options: ClassAOptions): ClassA {
return new ClassA(options);
}
}
type ClassBOptions = {
fooB: boolean;
barB: boolean;
};
class ClassB {
constructor(options: ClassBOptions) {}
static new(options: ClassBOptions): ClassB {
return new ClassB(options);
}
}
const classList = {
first: ClassA,
second: ClassB,
};
function createClass<K extends keyof typeof classList>(
className: K,
args: ConstructorParameters<typeof classList[K]>[0]
) {
// type error
// Argument of type 'ClassAOptions | ClassBOptions' is not assignable to parameter of type 'ClassAOptions & ClassBOptions'.
return new classList[className](->args<-);
}
createClass("first", { fooA: "false", barA: "false" });
createClass("second", { fooB: false, barB: false });
this type error is make me crazy, does anyone know why typescript will show an error here,
I can't find my answer on google at all;
Or let me know the key point of this type err, I can google it then