如何在类型描述中指定类定义作为参数类型
问题描述:
我想传递类的类型信息,同时暗示编译器指出给定的参数不是类的实例,而是类定义。我怎样才能做到这一点?如何在类型描述中指定类定义作为参数类型
import * as Routes from '../routes';
import * as Entities from '../entities';
export class RouteManager {
public router = Router();
private connection = getConnectionManager().get();
constructor() {
this.addRoute(Routes.VideoRoute, Entities.Video);
}
addRoute(routeClass: AbstractRoute<AbstractEntity>, entity: AbstractEntity): void {
const instance = new routeClass(entity, this.connection.getRepository(entity))
this.router.get(instance.route, instance.find);
}
}
在这里,编译器会抱怨的new routeClass(entity, this.connection.getRepository(entity))
线,因为它认为routeClass
是AbstractRoute<AbstractEntity>
一个实例,而不是出口类定义它。
我尝试过使用AbstractRoute<AbstractEntity>.constructor
,但Typescript似乎并不知道这个结构。
答
这样的语法看起来有点奇怪。基本上你可以定义一个使用类似new(...args: any[]) => T
的签名。您当然可以更严格地将T
替换为您的班级,将args
替换为constructor
签名。
我建议是这样的:
class Foo {}
type Constructor<T> = new(...args: any[]) => T;
function createFoo(thing: Constructor<Foo>) { return new thing(); }
+0
它引发以下内容:类型'typeof Video'不能分配到类型'构造函数
+0
在你的例子中没有'Video'类型,但从它的外观你多次使用相同的标识符。这也是错误告诉你的:*有这个名字的两种不同类型* PS:这似乎是你的代码的问题。你能否将我的示例代码复制/粘贴到代码库中,并检查它是否有效? –
您链接到这个问题o.O –
对不起! :D http://stackoverflow.com/questions/34698710/defining-typescript-generic-type-with-new –