Given an array of items that implemented a specific class with a generic type, I would like to create combined type from the array items - For each item, take its generic (defined as first generic argument for example) and create a type that implements all the the generic values of the items.
For Example:
// Defining 2 types with different set of methods
type ObjectWithMethods1 = {
call1(a: string): void;
}
type ObjectWithMethods2 = {
call2(): number;
}
class BaseItem<T> {
}
// Defining 2 classes that both extends the same class/abstract class,
// each passing a different generic value.
class Item1 implements BaseItem<ObjectWithMethods1> {
}
class Item2 implements BaseItem<ObjectWithMethods2> {
}
// An array that contains instances of the same base class, however each of its items
// used a different type in the BaseItem generics
const arr: BaseItem<any>[] = [new Item1(), new Item2()]
// How to define the typing of a "getCombinedObject" method that its return type will be an object
// that implements both ObjectWithMethods1 and ObjectWithMethods2,
// e.g. ObjectWithMethods1 & ObjectWithMethods2
const combined = getCombinedObject(arr);
combined.call1('test'); //void
combined.call2(); //number
I've tried achieving it in few different ways, can fetch the generic values of the array but failed to achieve the aggregated values of the array.
Its something conceptually similar to this (without the additional depth created due to the of the iteration of the array items):
type CombinedObject<TArray extends TItem[], TItem extends Record<string, any>> = {
[key: string]: {
[Index in keyof TArray]: TArray[Index] extends { [key]: any } ? TArray[Index][key] : never;
};
};
Thanks alot!