Feature Request: unwrapOrElse with default value #479
Replies: 2 comments 1 reply
-
Hmm. I see what you're going for here, but I don't think it actually makes sense to add this functionality to the library itself—you can imagine wanting to do the same with every That said, I think the thing you're trying to do can be solved pretty cleanly just using normal function composition. Instead of pushing it into True Myth, you should handle it with your own functions. That would look something like this: function handleErr<T, E>(defaultValue: T): (err: E) => T {
return (cause) => {
if (process.env.NODE_ENV !== 'production') {
throw new Error('Something went wrong', { cause });
}
return defaultValue;
};
} Then you just use that like this: const n = fallibleNumber(false).unwrapOrElse(handleErr(0));
const s = fallibleString(false).unwrapOrElse(handleErr(''));
const activeElement = fallibleActiveElement()
.unwrapOrElse(handleErr<Element | null, string>(null)); Here is a demo of that: TS playground. (Note the comment on the cast for the The nice thing here is that True Myth doesn't need to know anything about that pattern! Any function composition will work, whether that's doing side effects as here, or building it up via a pipeline of some other set of functions, or any other combination you can come up with. Instead of baking in some kind of specific handling for this one scenario, we have a fully general capability, just powered by function composition. |
Beta Was this translation helpful? Give feedback.
-
@chriskrycho you are right on everything. |
Beta Was this translation helpful? Give feedback.
-
What I am asking for is effectively to allow for
unwrapOrElse
to be anunwrapOr
with side effects.My use case is, having:
simplify this:
to this:
What I did here was passing a default value as a second argument to
unwrapOrElse
, which is then somehow made available as an optional second argument for theorElseFn
callback.Beta Was this translation helpful? Give feedback.
All reactions