To recreate or encapsulate the TypeScript typeof
operator as a generic type is not possible.
The TypeScript typeof
operator accepts a value like a variable or property as input, and returns the corresponding TypeScript data type of that value. For example, using typeof C1
interprets C1
as the value named C1
, which represents the constructor of the class C1
.
However, generic type parameters such as T
in the TGenericType<T>
defined type alias signify types rather than values. Therefore, the expression typeof T
becomes illogical since T
itself is a type. Consequently, this results in a compiler error:
type TGenericType<T> = typeof T; // error!
// -------------------------> ~
// 'T' only refers to a type, but is being used as a value here.
If attempting to resolve this issue, one might end up writing
type TGenericType<T> = T;
let test: TGenericType<typeof C1> = C1;
This approach offers no improvement over directly using typeof C1
; alternatively, one may consider that having TGenericType<C1>
output a constructor type where C1
signifies the instance:
type TGenericType<T> = new () => T;
let test: TGenericType<C1> = C1; // valid
Nonetheless, this does not directly relate to the C1
value, leading to potential loss of static properties if utilized to construct new instances of C1
:
class C1 {
static foo = 1;
bar = 2;
}
new C1().bar; // okay
new test().bar; // okay
C1.foo; // okay
test.foo // error
The preferred approach depends on the specific use case or the choice to relinquish the endeavor altogether.
Access code in Playground