flowtype:$ Subtype和typeof在泛型类型中使用时失败

时间:2017-08-14 03:20:52

标签: flowtype

流中的类类型似乎总是引用该类的实例,而一个类使用typeof来引用实际的类本身。所以,如果我想要一个变量来引用基类的子类(而不是实例),我可以这样做:

class MyBaseClass {}
class MySubClass extends MyBaseClass {}
let a: $Subtype<MyBaseClass> = MySubClass; // fails
let b: $Subtype<MyBaseClass> = new MySubClass(); // works, but I don't want this.
let c: $Subtype<typeof MyBaseClass> = MySubClass; // works! Ok, we're good

但是,我似乎无法使用类型参数执行此操作!例如,以下内容:

type GenericSubclass<T> = $Subtype<typeof T>;
// fails with `^ identifier `T`. Could not resolve name`

如果我尝试以下的Typescript技巧(参见Generic and typeof T in the parameters),它也会失败:

type ValidSubclass<T> = { new(): T };
const c: ValidSubclass<BaseClass> = MySubClass;
// fails with: property `new`. Property not found in statics of MySubClass

请注意,我尝试了new__proto__constructor

是什么给出的?有解决方法吗?

1 个答案:

答案 0 :(得分:2)

typeof MyBaseClass

Class<MyBaseClass>

所以你可以做到

type GenericSubclass<T> = $Subtype<Class<T>>;