[英]How to use a typescript generic class constructor as a parameter in a function call
I am trying to use the following API from the package typescript-json-serializer
.我正在尝试使用包
typescript-json-serializer
的以下 API。
export declare function deserialize<T>(json: object, type: new (...params: Array<any>) => T): T;
A simple working sample code for this API usage is:此 API 用法的简单工作示例代码是:
const result: MyClass = deserialize<MyClass>(json, MyClass);
My usage is a little more tricky.我的用法有点棘手。 Instead of
MyClass
, I would like to have a generic class, something like MyClass<T>
.而不是
MyClass
,我想要一个通用类,比如MyClass<T>
。
I tried the following, but it is failing to compile我尝试了以下方法,但无法编译
const result: MyClass<T> = deserialize<MyClass<T>>(json, MyClass<T>);
The mentioned error is Value of type 'typeof MyClass' is not callable. Did you mean to include 'new'?
提到的错误是
Value of type 'typeof MyClass' is not callable. Did you mean to include 'new'?
Value of type 'typeof MyClass' is not callable. Did you mean to include 'new'?
Any idea how to solve this ?知道如何解决这个问题吗?
Updates : In my last exemple, T is a real class.更新:在我的最后一个例子中,T 是一个真正的类。
const result: MyClass<MyClass2> = deserialize<MyClass<MyClass2>>(json, MyClass<MyClass2>);
The generic parameter of the constructor is implied by the T annotation on deserialize
.构造函数的一般参数是通过在T注释暗示的
deserialize
。 The correct and typesafe syntax is:正确且类型安全的语法是:
deserialize<MyClass<T>>(json, MyClass);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.