A simple zero dependency TypeScript empowered implementation of an Either construct for improved control flow and error handling
npm install ts-errorflowtypescript
interface ParkingLotFullError = {
tryAgainAt: Date;
}
interface Ticket {
ticketNumber: string;
issuedAt: Date;
}
function tryGetTicket(): Ticket | ParkingLotFullError {
if (lotIsFull()) {
return makeError({
tryAgainAt: new Date()
});
}
// return an actual ticket
}
const ticketResponse = tryGetTicket();
if (isError(ticketResponse)) {
// response is definitely an error and will only allow access of properties from ParkingLotFullError
} else {
// response is definitely a ticket and will only allow access of properties from Ticket
}
``