简体   繁体   English

如何在函数调用中使用打字稿泛型类构造函数作为参数

[英]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.

相关问题 Typescript,如何使用 class 的构造函数扩展抽象 class 作为参数 - Typescript, how to use a constructor of a class extending an abstract class as parameter 如何在 Typescript 中定义和调用通用 function 参数? - How do I define and call a generic function parameter in Typescript? 构造函数作为参数:将类的泛型推断为 function - Constructor as parameter: infer class's generic into function TypeScript 在咖喱中使用通用 function 参数 function - TypeScript use generic function parameter in curry function Typescript:将泛型类传递给函数参数 - Typescript: Pass generic class to function parameter TypeScript:如何在没有构造函数的 ZA2F2ED4F8EBC4061D456E5D3297Z function 内部调用 static function? - TypeScript: how to call a static function internally in a class without a constructor? 如何使TypeScript正确键入对泛型函数的检查调用,然后依次调用具有泛型类型参数的函数? - How can get TypeScript to correctly type check call to a generic function that in turns calls a function with a generic type parameter? 如何在 Typescript 中获取 class 的通用参数类型 - How to get Generic Parameter Type of class in Typescript 打字稿:如何使用通用参数作为对象键 - Typescript: How to use a generic parameter as object key Typescript 通用 class 带无参数构造函数 - Typescript generic class with parameterless constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM