I\'d like to make a function in TypeScript that takes an array of constructor functions and returns a corresponding array of instances. See code below.
Note that th
You can do this in TS3.1 and above using mapped array/tuple types. It's easier to get tuples inferred for rest parameters than it is for array parameters, so I'll show that instead:
function getVariadic<T extends Array<AnyCon>>(...cons: T): {
[K in keyof T]: T[K] extends AnyCon ? InstanceType<T[K]> : never
};
function getVariadic(...cons: AnyCon[]): any[] {
return cons.map((c: AnyCon) => new c());
}
let [t2, t3]: [T2, T3] = getVariadic(T2, T3);
This behaves as you expect, I think. Hope that helps. Good luck!
EDIT: if you really need to do it with an array it's easy to type the function but a little harder to call it in such a way that the order of the array is preserved as a tuple:
function getArray<T extends Array<AnyCon>>(cons: T): {
[K in keyof T]: T[K] extends AnyCon ? InstanceType<T[K]> : never
};
function getArray(cons: AnyCon[]): any[] {
return cons.map((c: AnyCon) => new c());
}
// error, getArray([T2, T3]) returns (T2 | T3)[]!
let [t2, t3]: [T2, T3] = getArray([T2, T3]); //