Skip to content

[request for help] - casting right type on left #251

Description

@stefaanMLB

I'm new to functional programming and I am probably doing this all wrong.
I very much like using Either to pass errors up the call chain.
In practice, I find myself using a type cast of the right side when the either is a Left very often which feels wrong.
This typically happens when a function in the middel of the call chain catches a left from a function down the chain that has a different Right type than the function itself.
I assume there must be a better way of doing this otherwise the cast function would probably be part of the library.

What is the better way ?

Here's an simplified example

function castRight_of_Left<RT>(either: Either<Error, unknown>) {
  return Left<Error, RT>(either.left())
}

public async getOrder(orderNumber: string): Promise<Either<Error, Order>> {
  let result = await this._orderRepo.getOrderByOrderNumber(orderNumber)             // returns Promise<Either<Error, Order | null>>
  if (result.isLeft()) return castRight_of_Left<Order_and_Sample>(result)           // Database error, pass the error up the call chain
  if (getSampleresult.right() == null) return Left(new Error(`order not found`))    // aanvraag niet gevonden
  const order = result.right()!

  // ... manipulations of the order object

  return Right(order)
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions