Issue
For example, I want to create a type that make some like below.
class C1 {}
type TGenericType<T> = typeof T;
let test: TGeneticType<C1>; //=> typeof C1
I don't want to have to pass a typeof
explicitly as a generic, like below
let test: TGeneticType<typeof C1>
Solution
There's no way to re-implement or wrap the TypeScript typeof
operator as a generic type.
The TypeScript typeof
operator takes a value such as a variable or property as an argument, and evaluates to the TypeScript type of that value. If you write typeof C1
, then C1
is interpreted as the value named C1
, which is the constructor of the C1
class.
But generic type parameters, like the T
in the TGenericType<T>
type alias, represent types and not values. So typeof T
does not make sense because T
is itself a type. Hence the compiler error:
type TGenericType<T> = typeof T; // error!
// -------------------------> ~
// 'T' only refers to a type, but is being used as a value here.
If you try to fix this, you'll either find yourself writing
type TGenericType<T> = T;
let test: TGenericType<typeof C1> = C1;
which is no better than just writing typeof C1
to start with; or, you'll decide that what you really want is for TGenericType<C1>
to produce a constructor type where C1
is the instance, which looks like this:
type TGenericType<T> = new () => T;
let test: TGenericType<C1> = C1; // okay
but that doesn't actually have anything to do with the C1
value, so while you could use this to construct new C1
instances, you would lose track of any static properties:
class C1 {
static foo = 1;
bar = 2;
}
new C1().bar; // okay
new test().bar; // okay
C1.foo; // okay
test.foo // error
It depends on your use case which of these you want to pursue, or whether you want to give up entirely.
Answered By - jcalz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.