Fp-ts: Either: get / extract / unbox

Created on 12 May 2018  路  4Comments  路  Source: gcanti/fp-ts

Hi, I'am quite new to FP and as far as I've read, extracting value from any type of monad is not favored. That's ok in the long run, however, for a smooth transition I am expecting to be able to extract the value from the Either monad. Can't I, really ? :)

say no to partial functions!

Most helpful comment

Oh that's interesting, if isRight() returns true, value property is just there.

Well, I've read so many articles/books that favor not to reach the boxed value directly, so I will try my best. Thanks

All 4 comments

You can't, you should use fold, getOrElse or getOrElseL which are safe.

However you can easily define your own unsafe get

const get = <L, A>(fa: Either<L, A>): A =>
  fa.getOrElseL(() => {
    throw new Error('get called on Left')
  })

(I don't recommend it though)

Oh ok. So when do you use isRight() ? Even if you become sure that it is a right, you cant extract the value

Is there any easy-to-follow code examples, like a tutorial or a small project I can understand the mindset?

isRight (both the method and the function) is defined as a custom type guard so you can do

declare const fa: Either<string, number>
if (fa.isRight()) {
  // const n: number
  const n = fa.value
}

since TypeScript is able to refine fa. IMO it must be used sparingly because that way you are not forced to handle the failing case.

Oh that's interesting, if isRight() returns true, value property is just there.

Well, I've read so many articles/books that favor not to reach the boxed value directly, so I will try my best. Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Crashthatch picture Crashthatch  路  4Comments

steida picture steida  路  4Comments

mattgrande picture mattgrande  路  3Comments

mmkal picture mmkal  路  3Comments

mohsensaremi picture mohsensaremi  路  3Comments