I am looking for a solution to wrap rxjs subscribe's next
callback with my own 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
}
};
}
The issue with the example below is that it does not automatically infer the type from subscribe's next
function. In this case, the user
type is identified as unknown
. The only way to set the user's desired type is by explicitly defining the type variable T in withTryCatch
(see commented code below - withTryCatch<UserModel>
).
store$
.pipe(
map(userSelector)
)
// .subscribe(withTryCatch<UserModel>((user) => {
.subscribe(withTryCatch((user) => {
// possible error code
}));
Is there a way to avoid using withTryCatch<UserModel>
?