typescript 引用构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12787259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Referencing the constructor function
提问by Jake H
Im wondering how I can get a reference to a types constructor to pass the function as a value. Basically, I would like to have a generic type registry that would allow instances to be created by calling a member function of a generic type registry instance.
我想知道如何获得对类型构造函数的引用以将函数作为值传递。基本上,我想要一个泛型类型注册表,它允许通过调用泛型类型注册表实例的成员函数来创建实例。
For example:
例如:
class GeometryTypeInfo
{
constructor (public typeId: number, public typeName: string, public fnCtor: (...args: any[]) => IGeometry) {
}
createInstance(...args: any[]) : IGeometry { return this.fnCtor(args); }
}
}
Later:
之后:
class Point implements IGeometry {
constructor(public x: number, public y: number) { }
public static type_info = new GeometryTypeInfo(1, 'POINT', Point); // <- fails
// also fails:
// new GeometryTypeInfo(1, 'POINT', new Point);
// new GeometryTypeInfo(1, 'POINT', Point.prototype);
// new GeometryTypeInfo(1, 'POINT', Point.bind(this));
}
Anyone know if it is possible to reference a classes constructor function?
任何人都知道是否可以引用类构造函数?
回答by Brian Terlson
You can use the constructor type literal or an object type literal with a construct signature to describe the type of a constructor (see, generally, section 3.5 of the language spec). To use your example, the following should work:
您可以使用构造函数类型文字或带有构造签名的对象类型文字来描述构造函数的类型(通常参见语言规范的第 3.5 节)。要使用您的示例,以下内容应该有效:
interface IGeometry {
x: number;
y: number;
}
class GeometryTypeInfo
{
constructor (public typeId: number, public typeName: string, public fnCtor: new (...args: any[]) => IGeometry) {
}
createInstance(...args: any[]) : IGeometry { return new this.fnCtor(args); }
}
class Point implements IGeometry {
constructor(public x: number, public y: number) { }
public static type_info = new GeometryTypeInfo(1, 'POINT', Point);
}
Notice the constructor type literal in GeometryTypeInfo's constructor parameter list, and the new call in the implementation of createInstance.
注意 的构造GeometryTypeInfo函数参数列表中的构造函数类型字面量,以及 的实现中的 new 调用createInstance。
回答by gaperton
typeof YourClassgives you constructor typewhich can be used in type annotations.
typeof YourClass为您提供可用于类型注释的构造函数类型。
YourClassand this.constructoris constructor itself. So, this code compiles:
YourClass并且this.constructor是构造函数本身。所以,这段代码编译:
class A {}
const B : typeof A = A;
this.constructoris not recognized as value of constructor type by TypeScript (which is funny), so in situations like that you need to use some cheating casting it no any
this.constructor不被 TypeScript 识别为构造函数类型的值(这很有趣),因此在这种情况下,您需要使用一些作弊来强制转换它不 any
new (<any> this.constructor)()
new (<any> this.constructor)()
That's it.
就是这样。

