0

How can we write a generic RXJS map function, and use it like an error handler applied to an Angular Http observable ?

I have tried :

registerUser(user: CreateUserAPI) {
  interface res  {
    session_key?: string;
    result?: string;
    error?: string;
  }

  return this.http
    .post<res>(`${API_URL}/api/customer/register`, user)
    .pipe(catchError(this.handleError), map(this.captureError));
}

captureError<T>(res: T): T {
  if (res.error) { // <== TS ERROR : Property 'error' does not exist on type 'T'
    Raven.captureMessage(res.error);
  }
  return res;
}

test(){
    let user : any
    this.registerUser(user).subscribe(res => {
      res.error // no error
    })
  }

But TS is returning the error : Property 'error' does not exist on type 'T'

My goal is to keep the typing of my observable when I subscribe to it later (test() method)

1 Answer 1

1

You can set that your generic type extends interface with error property:

interface ErrorObj {
  error: string;
}

captureError<T extends ErrorObj>(res: T): T {
  if (res.error) {
    Raven.captureMessage(res.error);
  }
  return res;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.