0

I want to wrap rxjs subscribe's next callback with my function:

type Handler<T> = (value: T) => void;

export function withTryCatch<T>(callback?: Handler<T>): Handler<T> {

  return (value: T) => {
    try {
      callback?.(value);
    } catch(err) {
      // error handling
    }
  };
}

Problem with this example bellow is, that it does not automatically infer type from subscribe's next function. In this example, user type is stated as unknown. Only way how to make user desired type, is to explicitly set withTryCatch type variable T (see commented code below - withTryCatch<UserModel>).

 store$
    .pipe(
      map(userSelector)
    )
    // .subscribe(withTryCatch<UserModel>((user) => {
    .subscribe(withTryCatch((user) => {
      // possible error code
    }));

Is there any way how to avoid using withTryCatch<UserModel>?

1 Answer 1

2

This issue is separated from place where you use withTryCatch function, in that case it's rxjs subscribe method. When you just invoke it the generic T type parameter is unknown. When you call it with some type parameter then T is of course known. You could use Typescript inferring by typing user argument like here:

withTryCatch((user: UserModel) => {

});

You need to pass callback directly to subscribe to use Typescript inferring. Unfortunately it is impossible with that kind of wrapper function

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.