简体   繁体   English

如何键入类或构造函数

[英]How to type a Class or Constructor

I'm using a similar pattern to this: 我正在使用与此类似的模式:

class MyClass { }

doSomethingWithClass(MyClass) { }

If I were to add typing to my code, using Flow or TS, how would I type this? 如果要使用Flow或TS在代码中添加键入内容,该如何键入? Wouldn't something like this imply that I'm expecting an instance of MyClass? 这样不是暗示我正在期待MyClass的实例吗?

doSomethingWithClass(MyClass: MyClass) { } 

What I want to do is pass the constructor/class into a factory pattern, but I don't know how to actually type it. 我想做的是将构造函数/类传递给工厂模式,但是我不知道如何实际键入它。

In order to pass a class constructor to a function you can use a constructor signature: 为了将类构造函数传递给函数,可以使用构造函数签名:

function doSomethingWithClassGeneric<T>(myClass: new () => T) { 
    return new myClass()
} 
doSomethingWithClassGeneric(MyClass);

Above we use a constructor with no arguments but you can potentially require parameters to the constructor to be present. 上面我们使用了不带参数的构造函数,但是您可能需要向构造函数提供参数。

Or you can also use typeof MyClass to accept classes derived from MyClass with a compatible constructor: 或者,您也可以使用typeof MyClass接受具有兼容构造函数的从MyClass派生的类:

class MyClass { }
class MyClassDerived extends MyClass  {  x!: number }

function doSomethingWithClassGeneric<T>(myClass: typeof MyClass) { 
    return new myClass()
} 
doSomethingWithClassGeneric(MyClass);
doSomethingWithClassGeneric(MyClassDerived);

Use the Class<> utility type. 使用Class <>实用程序类型。

class MyClass { };

function doSomethingWithClass(klass: Class<MyClass>): void {
}

doSomethingWithClass(MyClass)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM