Is there a way to use the typeof
operator to retrieve the constructor type from a class, specifically when dealing with a dictionary of classes? When trying to use it on a dictionary of classes like Modules[T]
, the compiler interprets it as (typeof Modules)[T] instead of obtaining the actual type of Modules[T]
.
class A { }
class B { }
abstract class Modules {
public a!: A;
public b!: B;
}
// Error: Type 'T' cannot be used to index type 'typeof Modules'
function addModule<T extends keyof Modules>(key: T, ModuleCtor: typeof Modules[T]) {
let module = new ModuleCtor();
}
addModule('a', A);
// Works but loses the constructor arguments type
function addModule2<T extends keyof Modules>(
key: T,
ModuleCtor: new (...args:any[]) => Modules[T]
) {
let module = new ModuleCtor();
}
addModule2('a', A);
Update
As Aleksey mentioned, the typeof
operator only works on values. Since classes are considered as actual values in JavaScript, what I have here are pure types. Essentially, I am searching for a solution that functions similar to typeof Class (value)
, which would enable me to retrieve the precise type of a constructor (including its arguments) for a pure class type.