0

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());
}
Kyle Pfromer
  • 1,485
  • 1
  • 15
  • 26

1 Answers1

1
createTask(task: Task): Observable<SavedTask> {
    return this.http.post<SavedTask>(`${url}/tasks`, task.asTask());
}
jonhid
  • 2,075
  • 1
  • 11
  • 18
  • I have tried this and it gets me the following error: `Type 'Observable' is not assignable to type 'Observable'. Type 'TemporaryTask' is not assignable to type 'SavedTask'. Property '_id' is missing in type 'TemporaryTask'.` – Kyle Pfromer Feb 26 '18 at 04:43
  • That worked, I didn't think that it would be this simple. Thanks! – Kyle Pfromer Feb 26 '18 at 04:51