我想知道为什么类型typeof T
和new() => T
不兼容。考虑一个getConstructor<T>
功能:TypeScript:typeof T不兼容{new():T}
function getConstructor<T>(instance: T)
{
return instance.constructor as new() => T;
}
let instance = new MyClass();
let x: typeof MyClass;
let y = getConstructor(instance);
x = y; // type error
的错误状态:类型new() => MyClass
是不能分配给类型typeof MyClass
。这可能是因为我的MyClass
有一些静态函数在new() => MyClass
中丢失。
因此,一个解决方案是使用typeof T
:
function getConstructor<T>(instance: T)
{
return instance.constructor as typeof T; // type error
}
然而,这给了我另一种类型的错误:T
仅是指一类,但被用作这里的值。
打字稿语言规范中4.18.6节规定: 在位置处一个类型的预期,“的typeof”也可以在一种类型的查询中使用的[...],以产生 表达式的类型。
那么为什么会出现上述类型的错误呢?无论如何,有什么办法可以做到这一点?
你能分享一个指向TypeScript Playground第一个例子的基本代码的链接吗? http://www.typescriptlang.org/play/ –