例如,我想创建一个如下所示的类型.
class C1 {}
type TGenericType<T> = typeof T;
let test: TGeneticType<C1>; //=> typeof C1
我不想显式地将typeof
作为泛型传递,如下所示
let test: TGeneticType<typeof C1>
例如,我想创建一个如下所示的类型.
class C1 {}
type TGenericType<T> = typeof T;
let test: TGeneticType<C1>; //=> typeof C1
我不想显式地将typeof
作为泛型传递,如下所示
let test: TGeneticType<typeof C1>
没有办法将TypeScript typeof
operator重新实现或包装为generic类型.
类型脚本typeof
运算符将变量或属性之类的value作为参数,并计算为该值的类型.如果您编写typeof C1
,则C1
将被解释为名为C1
的值,它是C1
类的构造函数.
但是泛型类型参数,如TGenericType<T>
type alias中的T
,表示types而不是值.因此,typeof T
没有意义,因为T
本身就是一种类型.因此出现编译器错误:
type TGenericType<T> = typeof T; // error!
// -------------------------> ~
// 'T' only refers to a type, but is being used as a value here.
如果你想解决这个问题,你要么会发现自己在写
type TGenericType<T> = T;
let test: TGenericType<typeof C1> = C1;
这并不比从typeof C1
开始好;或者,你会决定你真正想要的是TGenericType<C1>
产生一个constructor type,其中C1
是实例,看起来像这样:
type TGenericType<T> = new () => T;
let test: TGenericType<C1> = C1; // okay
但这实际上与C1
值没有任何关系,因此,虽然您可以使用它来构造新的C1
个实例,但您可能会忘记任何静态属性:
class C1 {
static foo = 1;
bar = 2;
}
new C1().bar; // okay
new test().bar; // okay
C1.foo; // okay
test.foo // error
这取决于您的用例,您想要使用其中的哪一个,或者您是否想要完全放弃.