I am currently attempting to obtain an instance of a Sequence class that contains an array of various Request objects, each following the same pattern. Each Request object consists of an operation
property (a string) and a property with the value of the respective operation.
The challenge I am facing is figuring out how to maintain the types of these Request objects when passing them to the Sequence class.
I may have misunderstood generics, or possibly overcomplicated this scenario with redundancy. The main requirement here is to have a Sequence class that includes all the Requests while utilizing some TypeScript magic.
I would greatly appreciate any assistance you can provide on this matter.
// Using this approach to work around the generic Request class in the Sequence class
class BaseRequest {}
class Request<T> extends BaseRequest {
constructor(params: T) {
super();
Object.assign(this, params);
}
}
class Sequence {
requests: BaseRequest[];
add(request: BaseRequest) {
this.requests.push(requests);
}
merge(sequence: Sequence) {
this.requests = this.requests.concat(sequence.requests);
}
}
const RequestBuilder = <T>(payload: T) => {
return <T>new Request(<T>payload);
}
interface CreateJobRequest {
operation: 'createJob';
createJob: any;
}
const params: CreateJobRequest = {
operation: 'createJob',
createJob: {},
};
let request = RequestBuilder(params);
let sequence = new Sequence();
sequence.requests.push(request);
When attempting to access that request, the error message received is:
// Property 'operation' does not exist on type 'BaseRequest'
if (sequence.requests[0].operation === '') {}
The following code snippet doesn't resolve the issue either (without using the builder):
class JobRequest extends BaseRequest implements CreateJobRequest {
operation: 'createJob' = 'createJob';
createJob: any = {};
constructor() {
super();
}
}
let sequence = new Sequence();
sequence.requests.push(new JobRequest());