Re: [whatwg/dom] Improving ergonomics of events with Observable (#544)

Congrats all for bringing this proposal 🎉. I just want to address a point that I think the current implementation of RxJs is missing.

Currently, both Promises and Observables can only be typed on the value, not on the error. And I know talking about types (TypeScript or flow) is a strange thing to do in an Observable proposal, but the underlying reason is a subtle one, and the behaviour of how Observables handle different error situations is paramount.

The problem, as stated [here](https://github.com/Microsoft/TypeScript/issues/7588#issuecomment-251497451), arrise when handling functions that *throws* errors, for example

```
Observable
  .of(1)
  .map(_ => {throw 'ups'})
  .fork(
       x => x,
       err => err // The error will be the string 'ups', but the type checker can only type it as any
  );
```

We can't avoid to handle these types of error as either your functions or functions that you call may throw, but on the other hand this type of error handling goes against of how we should do it functionally. It would be better to use a chainable method like `.switchMap` and `Observable.throw` or in the case of promises `.then` and `Promise.reject`.

For that reason, both Promises and Observables can only be typed on error as `any` and sadly it is the correct type. Luckly I think there are at least two possible solutions, one that is relevant to the Observable proposal. 

One solution would be to `try catch` all methods that may throw and wrap the possible error into a class that extends from `Error`, for example

```
class UncaughtError extends Error {
}
```

which would make the following example possible

```
Observable
  .of(1)
  .map(_ => {throw 'ups'})
  .switchMap(_ => Observable.throw(new DatabaseError())
  .fork(
       x => x,
       err => err // The error type would be UncaughtError | DatabaseError
  );
```
Note that UncaughtError is always a posibility both if you have a function that throws or not but DatabaseError could be infered from the types of `Observable.throw` and `switchMap`.

Very recently I created a Promise like library called [Task](https://github.com/acamica/task) (WIP) that takes this into account and allow us to type both success and error cases. So far the results where more than satisfying.

The other solution I can think of would be if TypeScript or flow implements typed exceptions, but I don't think is the path their plans.

I hope you take this situations under consideration and thanks for the great work

Cheers!


-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/544#issuecomment-351484258

Received on Wednesday, 13 December 2017 18:45:09 UTC