2017-08-11 175 views
0

我想知道为什么类型typeof Tnew() => 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”也可以在一种类型的查询中使用的[...],以产生 表达式的类型。

那么为什么会出现上述类型的错误呢?无论如何,有什么办法可以做到这一点?

+0

你能分享一个指向TypeScript Playground第一个例子的基本代码的链接吗? http://www.typescriptlang.org/play/ –

回答

1

你的困惑的事实,MyClass(只打字稿知道,在运行时被擦除)的名字,同时也是一个(这是存在于JavaScript对象的名字的词干运行)。 类型MyClass适用于该类的实例,而MyClass是一个构造函数。

TypeScript允许您使用typeof运算符查询的类型。所以,typeof MyClass指的是MyClass的构造函数的类型。您无法查询类型的类型,因此,例如,typeof string是错误的(除非巧合地命名为string)。所以你不能做typeof T其中T是某种类型。


我还没有找到一个伟大的方式给你想要的东西。 TypeScript不知道如何从实例中推断出constructor属性的确切类型。它只是认为它是Function。我能做的最好的事情是明确标记类声明为正确类型的constructor。像这样:

interface Constructable<T, C extends Constructor<T>> { 
    "constructor": C 
} 

class MyClass implements Constructable<MyClass, typeof MyClass> { 
    "constructor" = MyClass; 
    // static methods, etc; 
} 

function getConstructor<C extends Constructor<{}>>(instance: Constructable<{},C>) 
{ 
    return instance.constructor; 
} 

let instance = new MyClass(); 
let x: typeof MyClass; 
let y = getConstructor(instance); 
x = y; // no error 

不知道你是否可以为你的课程做到这一点。希望有所帮助。祝你好运!

相关问题