I've developed a mergeClass function that merges properties from multiple classes into one variable instance. Currently, the function requires three classes to be merged, but I'm looking for a way to allow any number of classes to be merged together. Is this even possible? If not, please let me know. Thanks.
type Constructable = new (...args: any[]) => any;
const mergeClasses = <S extends Constructable, T extends Constructable, P extends Constructable>(class1: S, class2: T, class3: P) =>
<Si extends InstanceType<S> = InstanceType<S>,
Ti extends InstanceType<T> = InstanceType<T>,
Pi extends InstanceType<P> = InstanceType<P>>
(args1: ConstructorParameters<S>, args2: ConstructorParameters<T>, args3: ConstructorParameters<P>): Si & Ti & Pi => {
const obj1 = new class1(...args1);
const obj2 = new class2(...args2);
const obj3 = new class3(...args3);
for (const p in obj2) {
obj1[p] = obj2[p];
}
for(const p in obj3){
obj1[p] = obj3[p];
}
return obj1 as Si & Ti & Pi;
};
//Is it possible to do something like this in my mergeClasses function?
for(let i = 0; i<classes.length; i++){
let obj = classes[i]
const obj1 = new obj();
for (const p in obj) {
obj1[p] = obj[p];
}
}
const mergeE = mergeClasses(B, C, D);
const e = mergeE<B, C, D>([], [], []);
Check out the MergeClasses Function in TypeScript Playground
I know this question may receive some criticism, and that's okay. If you have an answer or insights on whether achieving this task is feasible, feel free to share your thoughts. Your feedback is valuable. Thank you!