[英]Convert the Normal class to generic in typescript
I have a class to get JSON objects and convert them to the class that I want.我有一个类来获取 JSON 对象并将它们转换为我想要的类。 the code is below.
代码如下。
import {plainToClass} from "class-transformer";
import UserDto from "../../auth/dto/user.dto";
class ConvertJson {
userData(data) {
return plainToClass(UserDto, data);
}
}
when I want to convert the class to generaic class当我想将类转换为通用类时
import {plainToClass} from "class-transformer";
import UserDto from "../../auth/dto/user.dto";
class ConvertJson<T> {
userData(data) {
return plainToClass(T, data);
}
}
I get this error我收到这个错误
T only refers to a type, but is being used as a value here
T 仅指一种类型,但在这里用作值
After tweaking the code I found out that typescript generic is very different from C# or other languages so I convert the code to this so it has a generic vibe but not syntax.调整代码后,我发现 typescript generic 与 C# 或其他语言非常不同,所以我将代码转换为这个,因此它具有通用的氛围,但没有语法。
import {plainToClass} from "class-transformer";
interface IClass {
new (...args : any[])
}
class ConvertJson {
constructor(private dto : IClass) {
}
userData(data) {
return plainToClass(this.dto, data);
}
}
the reason I use IClass instead of any is that I want to make sure other teammates use class, not other types.
我使用 IClass 而不是 any 的原因是我想确保其他队友使用类,而不是其他类型。
I guess want you want to do is cast the output according to the input type我想你想做的是根据输入类型转换输出
class ConvertJson<T> {
userData(data) {
return <T>plainToClass(data);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.