5 ms·
You don't actually need the tag on Either. This is how I defined my Result type. The shape is enough to discriminate them. type Result<S, E> = Success<S> |
by tym0 6y ago
You don't actually need the tag on Either. This is how I defined my Result type. The shape is enough to discriminate them.
type Result<S, E> = Success<S> | ResultError<E>;
type Success<S> = { value: S };
type ResultError<E> = { error: E };
- valand 6y agoAuthor here. Did this too. I found some quirks (rather irrelevant) while compiling using TypeScript 3.6-ish. ``` const { value, error } = result; if (error) return doSomething(); if (value) return doSomethingElse(); ``` ^ You can't do this because value or error might be not an attribute of result Nowadays I will just `npm install fp-ts` and use them.
- tym0 6y agoYou're right that you can't destructure until you've established which side of the union you got, does the tag help with that? I like a Result type over an Either because it feels semantically more meaningful. I work with people with a wide range of background and a Result type is self explanatory, they can just read the code by themselves without knowing and understanding the convention of which side of the branch the error goes, etc...
- valand 6y agoI agree with you on the Result type being semantically more meaningful and I agree there are a lot of conventions to be remembered coming from functional programming that gets meta. Thanks for the insight