This TypeScript project demonstrates the usage of the Either pattern, a functional programming concept, to handle success and error scenarios in a more expressive and composable way. The Either type can represent either a success value (Right
) or an error value (Left
), providing a clean and structured way to handle different outcomes.
Ensure you have Node.js installed on your machine.
-
Clone the repository:
git clone https://github.com/gustavovalle23/either-pattern
-
Navigate to the project directory:
cd either-pattern
-
Install dependencies:
yarn install
To use the Either pattern in your TypeScript project, import the Either
class from the either.ts
file. The Either
class takes two type parameters: the success type and the error type.
import { Either } from './either';
// Example usage
const result: Either<string, number> = Either.right(42);
result.match({
left: (error) => console.error(`Error: ${error}`),
right: (value) => console.log(`Success: ${value}`),
});
import { Either } from './either';
const successResult: Either<string, number> = Either.right(42);
successResult.match({
left: (error) => console.error(`Error: ${error}`),
right: (value) => console.log(`Success: ${value}`),
});
import { Either } from './either';
const errorResult: Either<string, number> = Either.left('An error occurred');
errorResult.match({
left: (error) => console.error(`Error: ${error}`),
right: (value) => console.log(`Success: ${value}`),
});
import { Either } from './either';
function divide(x: number, y: number): Either<string, number> {
if (y === 0) {
return Either.left('Division by zero');
}
return Either.right(x / y);
}
const result = divide(10, 2)
.flatMap((value) => divide(value, 5))
.match({
left: (error) => console.error(`Error: ${error}`),
right: (value) => console.log(`Success: ${value}`),
});
This project is licensed under the MIT License - see the LICENSE file for details.