Make promise utils result union uniform
Siegrift opened this issue · comments
I've noticed that TS inference improved starting from version 4.6 which remembers relationships of the types even when they are destructured... This would allow us to make the results uniform and the following could work:
const { success, error, data } = goSync(() => 123);
// @ts-expect-error should not work
const x: number = data;
if (success) {
const xx: number = data;
}
Currently, you are only able to access the success
property before accessing the data
or error
properties. See the proposal in TS playground
For reference, this is already how useQuery
from react-query
works.
Can you give an example of what is it good for? I quite like that you can't access other fields than success
without checking its value. It kinda forces you to do the error handling which is what you usually want.
Without checking the success
the type of data: T | undefined
. Only after you check the success property you'll get data: T
. And there is no reason for preventing access to these properties.
Without checking the success the type of data: T | undefined. Only after you check the success property you'll get data: T
But that's the point. It's telling you to check it.
And there is no reason for preventing access to these properties.
Again, it's kind of a point of it. It forces you to check and that check is most likely some kind of error handling.
But that's the point. It's telling you to check it.
Yeah. It tell you to check the property for undefined
before using it, but also allows you to access the property. E.g.
const maybeLog = (e: Error | undefined) => {
if (e) console.error(e)
}
const goRes = await go(...)
maybeLog(goRes.error)
vs
const maybeLog = (e: Error | undefined) => {
if (e) console.error(e)
}
const goRes = await go(...)
if (goRes.error) maybeLog(goRes.error)