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>?