TypeScript: typeof T not compatible with { new(): T }
我想知道为什么
1 2 3 4 5 6 7 8 9 | 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 |
错误状态:类型
因此,一种解决方案是使用
1 2 3 4 | function getConstructor< T >( instance: T ) { return instance.constructor as typeof T; // type error } |
但是,这给了我另一个类型错误:
TypeScript语言规范在第4.18.6节中规定:
在需要类型的位置,也可以在类型查询中使用" typeof"来生成
表达式的类型。
那么,为什么会出现上述类型错误? 并且有某种方法可以使这项工作吗?
您感到困惑的原因是
TypeScript允许您使用
我还没有找到给您想要的东西的好方法。 TypeScript不知道如何从实例中推断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 |
不知道是否可以对您的班级做到这一点。希望能有所帮助。祝好运!