In angular 5 I am trying to create a POST that sends data of one type, in this case, TemporaryTask, and receive the POST response as a different data type, SavedTask. The problem is that Observable<TemporaryTask>' is not assignable to type 'Observable<SavedTask>
I know that you can get the response and then manually map it to a different type, seen here, but it is clunky. Is there a way to tell angular's HttpClient POST to cast the data to something new?
Note: each class is in its own file.
export abstract class Task {
description: string;
complete: boolean;
constructor(task: {description: string, complete: boolean}) {
this.description = task.description;
this.complete = task.complete;
}
asTask() {
return {
description: this.description,
complete: this.complete
};
}
}
export class SavedTask extends Task {
readonly _id: string;
description: string;
complete: boolean;
constructor(task: { _id: string, description: string, complete: boolean }) {
super({
description: task.description,
complete: task.complete
});
this._id = task._id;
}
}
export class TemporaryTask extends Task {
tempId: string;
constructor(task: {tempId: string, description: string, complete: boolean}) {
super({
description: task.description,
complete: task.complete
});
this.tempId = task.tempId;
}
}
This is where the error occurs
createTask(task: TemporaryTask): Observable<SavedTask> {
return this.http.post<TemporaryTask>(`${url}/tasks`, task.asTask());
}