[英]How can I use a Class returned by a function as a type in TypeScript?
I am working on a small library that contains a utility function that generates a Class. 我正在研究一个小型库,其中包含一个生成类的实用程序函数。 This is because the Class has quite a complex signature with a lot of generics.
这是因为Class具有很多泛型,因此具有相当复杂的签名。 It looks somewhat like this:
它看起来像这样:
function generateClass() {
class GeneratedClass {
...
}
return GeneratedClass;
}
The compiler correctly infers the return type of this function. 编译器正确推断此函数的返回类型。 The only problem is, I cannot use the returned value as a type.
唯一的问题是,我不能将返回值用作类型。 This only works if I extend the returned GeneratedClass.
这仅在我扩展返回的GeneratedClass时有效。 For a more elaborate example, see this TS Playground snippet .
有关更详细的示例,请参见此TS Playground片段 。
Is there any way to make the returned class usable as a type? 有什么方法可以使返回的类用作类型? I would rather not require consumers of my library to type
class Something extends generateClass() { ... }
, because that kind of defeats the purpose of the utility function making it more convenient to create these kinds classes. 我宁愿不要求我的库的使用者键入
class Something extends generateClass() { ... }
,因为class Something extends generateClass() { ... }
,因为这种方法破坏了实用程序功能的目的,使创建此类类更加方便。
You can get the instance type in several ways: 您可以通过几种方式获取实例类型:
If you have an instance of the class you can use typeof
with that variable to type the parameter: 如果您有该类的实例,则可以将
typeof
与该变量一起使用以键入参数:
const FooClass = generateClass();
const foo = new FooClass(5);
function processFoo(fooParam: typeof foo) {
}
In typescript 2.8 you can use the conditional type InstanceType
: 在打字稿2.8中,您可以使用条件类型
InstanceType
:
const FooClass = generateClass();
const foo = new FooClass(5);
function processFoo(fooParam: InstanceType<typeof FooClass>) {
}
processFoo(foo);
Pre 2.8 you can get the instance type without instatiating using a helper function and a dummy variable: 在2.8之前的版本中,您可以使用辅助函数和虚拟变量获取实例类型而无需实例化:
const foo = (function<T>(arg: new (...args: any[])=> T) : T{ return null as any})(FooClass);
function processFoo(fooParam: typeof foo) {
}
processFoo(foo);
In either case you can store the instance type in a type
alias to use in several places: 无论哪种情况,都可以将实例类型存储在
type
别名中,以在多个地方使用:
type GeneratedClass = typeof foo;
type GeneratedClass = InstanceType<typeof FooClass>; // for 2.8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.