I'm trying to use mapped types with typescript, which is supposed to be possible, but running into some issues.
Let's say I have 3 classes:
class A {
public foo1 = 1;
}
class B {
public foo2 = 1;
}
class C {
public foo3 = 1;
}
const base = [A, B, C] as const;
Basically, what I want is to pass base into some function, and get back an array with 3 matching instances.
type CTOR = new(...args: any[]) => any
function instantiate1<T extends ReadonlyArray<CTOR>>(arr: T): {[K in keyof T]: T[K]} {
const items = arr.map(ctor => new ctor());
return items as any; //Don't mind about breaking type safety inside the function
}
Now this returns:
const result1 = instantiate2(base) //type is [typeof A, typeof B, typeof C]
which makes sense, as I didn't really "map" the type yet, just made sure the syntax works.
However if I try to actually map the type:
function instantiate2<T extends ReadonlyArray<CTOR>>(arr: T): {[K in keyof T]: InstanceType<T[K]>} {
const items = arr.map(ctor => new ctor());
return items as any; //Don't mind about breaking type safety inside the function
}
I get an error that T[K] doesn't satisfy the constraint of instance type.
anyone as an idea for a workaround?