I'm coming to you because I've exhausted all of the Google recommendations. I'm trying to create a websocket system that will handle statically typed requests and responses.
I'm generating the request/response types from another project. I have two base types (RequestData and ResponseData) and a "GenericRequest" that the user will interact with when trying to send new requests. An example looks like this:
export class RequestData {}
export class ResponseData {}
export class GenericRequest<T extends RequestData, V extends ResponseData> {}
interface HandshakeResponseData extends ResponseData {
AuthCode: string;
RequestId: number; //unsigned
RedirectUrl: string;
}
interface HandshakeRequestData extends RequestData {
AuthCode: string;
RequestId: number; //unsigned
SessionToken: string;
}
export class HandshakeRequest extends GenericRequest<HandshakeRequestData, HandshakeResponseData> {}
Here is an example of it's usage.
new HandshakeRequest({
AuthCode: "0",
SessionToken: "<jwt>"
}).send(socket).then((data) => {
// response handler logic
});
There is a function within GenericRequest<T,V> called send() that sends a request off and waits for a response. When the response comes back, it is supposed to convert the response json into a ResponseData instance of type V. I'm having trouble creating the new instance of ResponseData from the generic argument V:
private create<R> (type: { new(): R} ) : R {
return new type();
}
^ This is the method of instantiating a generic type I've seen all over Stack Overflow, but it doesn't seem to work for me when I do this:
foo() : V { // where V corresponds to generic argument of GenericRequest<T,V>
return this.create<V>(V);
}
I get an error on the parameter within the parenthesis:
'V' only refers to a type, but is being used as a value here. ts(2693)
Here is the most minimum reproducible sample I could think of. I'd like to instantiate a new V object where V in Foo<V>
class Foo<V> {
constructor() {
}
create<V>(type: { new(): V} ) : V {
return new type();
}
thisIsTheError() {
let bar: V = this.create<V>(V);
}
}