我正在使用Cerialize作为Json序列化器/反序列化器。
我的Api连接器以这种方式工作:
ApiService.get<T>(endpoint:string):Promise<T>
来电
ApiConnectorService.get<ApiResponse<T>>(tClazz:{new():T;}, endpoint:string);
要反序列化,Cerialize使用类参数:
function Deserialize(json: any, type?: Function | ISerializable): any;
因此,当我呼叫时ApiService.get<T>(endpoint)
,我会呼叫ApiConnectorService.get<ApiResponse<T>>(ApiResponse, endpoint)
它。
ApiResponse<T>
编译器说我无法提供tClazz参数
TS1109:期望表达
有没有一种方法可以为泛型类提供其泛型类型作为参数?这样,当我打电话给get<User>()
我时,我得到一个ApiResponse<User>
类型的用户,此刻我只在ApiResponse中得到一个对象,这不是我们所需要的。
这是ApiResponse类:
export class ApiResponse<T>{
@deserialize
data:T;
@deserializeAs(ErrorData)
error:ErrorData;
@deserialize
meta:Object;
}
编辑:如果我想给一个数组作为类参数相同的错误:
ApiService.get<Foo[]>(Foo[], '/bar');
TS1109:期望表达
如果您在此处查看已转换的泛型类,则不会:Typescript Playground会释放泛型,因此在运行时您没有类型,因此无法获取泛型的类型,这意味着在运行时中您无法知道您的类型是什么T.您必须将类本身作为参数传递。您可以使用泛型获得编译帮助,但这就是您能做到的最好的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句