When working with TypeScript, I have a regular method called
Request(method: HttpMethod, url: string, ...)
that is used for calling APIs.
Now, my goal is to convert the response from this API request into an instance of a class using class-transformer
(or maybe without it).
For example:
class UserResponse {
id: number;
foo: string;
bar: string;
}
const user = await Request(HttpMethod.GET, '/user/1');
// The 'user' object should be an instance of the 'UserResponse' class
I am aware that using generics in this manner is not valid:
const Request = <T>(method: HttpMethod, url: string, ...) => {
// logic to fetch data...
return plainToClass(T, res);
}
const user = await Request<UserResponse>(HttpMethod.GET, '/user/1');
Although generics do not function in that way, there is a workaround like this:
const Request = <T>(method: HttpMethod, url: string, ..., transformTo?: { new (): T }) => {
// axios or other fetching mechanism...
return plainToClass(transformTo, res);
}
const user = await Request(HttpMethod.GET, '/user/1', ..., new UserResponse());
However, even this approach is still giving me a type of 'unknown' for the 'user' object:
const user: unknown
What mistake am I making here?